I must combine or implode subarray values if the product will be the same for any company.
Expected output should be like:
0 =>
array (
\'compa
implode()
is not going to be part of a simple/direct solution. You should assign temporary keys using the product values so that you can determine, during each iteration, if you are dealing with the first occurrence (store the whole subarray) or a subsequent occurrence of a product (append/concatenate the new company value using a comma as glue).
When finished iterating, re-index the array with array_values()
.
Code: Demo
$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,
),
)