implode()
不会成为简单/直接解决方案的一部分。您应该使用产品值分配临时键,以便您可以在每次迭代期间确定您正在处理产品的第一次出现(存储整个子数组)还是后续出现的产品(使用附加/连接新公司值)逗号作为粘合剂)。
完成迭代后,使用以下命令重新索引数组array_values()
.
Code: Demo https://3v4l.org/X718h
$array = array (
0 =>
array (
'company' => 1,
'product' => 5,
),
1 =>
array (
'company' => 2,
'product' => 4,
),
2 =>
array (
'company' => 6,
'product' => 5,
),
3 =>
array (
'company' => 2,
'product' => 3,
),
);
foreach ($array as $set) {
if (!isset($result[$set['product']])) {
$result[$set['product']] = $set;
} else {
$result[$set['product']]['company'] .= ",{$set['company']}";
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'company' => '1,6',
'product' => 5,
),
1 =>
array (
'company' => 2,
'product' => 4,
),
2 =>
array (
'company' => 2,
'product' => 3,
),
)