<?php
class Foo {
private $groupId;
private $value;
function __construct($groupId, $value) {
$this->groupId = $groupId;
$this->value = $value;
}
function getGroupId() {
return $this->groupId;
}
};
$foos = [
new Foo(1, 'Bar'),
new Foo(1, 'Ban'),
new Foo(1, 'Bak'),
new Foo(2, 'Gas'),
new Foo(2, 'Gar'),
];
var_dump(array_reduce($foos, function($carry, $item){
if(!isset($carry[$item->getGroupId()])) {
$carry[$item->getGroupId()] = [];
}
$carry[$item->getGroupId()][] = $item;
return $carry;
}, []));
preferences:
26.86 ms | 405 KiB | 5 Q