<?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.28, 8.2.0 - 8.2.19, 8.3.0 - 8.3.4, 8.3.6 - 8.3.7
- 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"
}
}
}
- Output for 8.3.5
- Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
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:
155.3 ms | 403 KiB | 211 Q