<?php
$input_array = [
['id' => 2, 'name' => 'ProductName', 'comment' => 'best product comment 1'],
['id' => 2, 'name' => 'ProductName', 'comment' => 'best product comment 2'],
['id' => 2, 'name' => 'ProductName', 'comment' => 'best product comment 3'],
['id' => 3, 'name' => 'ProductName2', 'comment' => 'best product comment 4'],
['id' => 3, 'name' => 'ProductName2', 'comment' => 'best product comment 5']
];
$output_array = array_values(array_reduce($input_array, function($output_array, $item) {
if (array_key_exists($item['id'], $output_array))
$output_array[$item['id']]['comment'][] = $item['comment'];
else
{
$item['comment'] = (array)$item['comment'];
$output_array[$item['id']] = $item;
}
return $output_array;
}, []));
var_dump($output_array);
- Output for 5.6.38, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.25, 8.4.1 - 8.4.12
- array(2) {
[0]=>
array(3) {
["id"]=>
int(2)
["name"]=>
string(11) "ProductName"
["comment"]=>
array(3) {
[0]=>
string(22) "best product comment 1"
[1]=>
string(22) "best product comment 2"
[2]=>
string(22) "best product comment 3"
}
}
[1]=>
array(3) {
["id"]=>
int(3)
["name"]=>
string(12) "ProductName2"
["comment"]=>
array(2) {
[0]=>
string(22) "best product comment 4"
[1]=>
string(22) "best product comment 5"
}
}
}
preferences:
136.91 ms | 409 KiB | 5 Q