php - Merge rows between two arrays of objects based on column value
Solution:
Merging objects is noticeably more tedious than arrays. I'd be tempted to convert the array of objects to an array or arrays in my own project, but I won't for this solution.
Unlike arrays which can enjoyarray_merge()
or the union operator, objects need to be pushed in manually.
I am temporarily grouping data by using theid
values as first level keys in the loop, then optionally sorting by those keys, then re-indexing the output to remove the temporary keys.
Code: (Demo):
$output = [];
foreach ($poorly_merged as $object) {
if (!isset($output[$object->id])) {
$output[$object->id] = $object;
} else {
foreach ($object as $property => $value) {
$output[$object->id]->{$property} = $value;
}
}
}
ksort($output); // optionally order by ids
var_export(array_values($output));
Or:
$output = [];
foreach ($poorly_merged as $object) {
if (!isset($output[$object->id])) {
$output[$object->id] = (object)[];
}
foreach ($object as $property => $value) {
$output[$object->id]->{$property} = $value;
}
}
ksort($output); // optionally order by ids
var_export(array_values($output));
Better practice would be not to merge your twp input arrays to form the$poorly_merged
array. You could use iterate the second array of objects and add that data into the first -- this would be a more direct solution.