php - Merge rows between two arrays of objects based on column value

84

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.

People are also looking for solutions to the problem: php - captcha code interfering with form handler

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.