<?php
## the user "class"
class Foo {
public int $id;
public string $foo;
public ?string $group = null;
public function __construct(int $id, string $foo) {
$this->id = $id;
$this->foo = $foo;
}
}
## users db result
$users_array = [
new Foo(999, 'abc'),
new Foo(4, 'abc'),
new Foo(5, 'xyz'),
new Foo(8, 'xxx')
];
## get IDs and build index
$index = [];
$ids = array_reduce($users_array, function(?array $ids, Foo $object) use(&$index) {
$ids[] = $object->id;
$index[$object->id] = $object;
return $ids;
});
### Groups, fetched from SQL
$groups = [
[ 'id' => 999, 'group' => 'group1'],
[ 'id' => 8, 'group' => 'group2'],
[ 'id' => 4, 'group' => 'group3'],
];
### stiching
foreach ($groups as $row) {
$index[$row['id']]->group = $row['group'];
}
## now the original array of users have their "group" property populated from the groups query
var_dump($users_array);