<?php
$data = [
['id' => 111, 'text' => 'yellow'],
['id' => 111, 'text' => 'red'],
['id' => 112, 'text' => 'green'],
];
$result = array_map(function($item) {return [
'id' => $item['id'],
'text' => implode(', ', $item['colors']),
];}, array_reduce($data, function($reduced, $item){
if (!isset($reduced[$item['id']])) $reduced[$item['id']] = $item;
$reduced[$item['id']]['colors'][] = $item['text'];
return $reduced;
}, []));
var_dump($result);
- Output for 7.1.25 - 7.1.30, 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.18, 8.3.0 - 8.3.6
- array(2) {
[111]=>
array(2) {
["id"]=>
int(111)
["text"]=>
string(11) "yellow, red"
}
[112]=>
array(2) {
["id"]=>
int(112)
["text"]=>
string(5) "green"
}
}
preferences:
124.86 ms | 403 KiB | 168 Q