2

I have a JSON array of multiple objects, here's an example:

$people = [{"name":"John", "color":"green"}, 
           {"name":"Mary", "color":"green"}, 
           {"name":"Bob", "color":"red"}]

I use json_decode($people, true) to convert them to an array...

Now let's say I want to combine those that have the same color. I'd have to do array_merge_recursive($people[0], $people[1]) because they both have green as the color. Note that I have to specify which ones I want to merge recursively.

How can I loop through $people after it's been decoded to an array format and automatically merge recursively those that have the same key value?

Something like this:

foreach($people as $person) {
    // If a person has same color of previous
    // person then merge them recursively.
}

So that I could get this after looping:

[{"name":"John, Mary", "color":"green, green"}, 
 {"name":"Bob", "color":"red"}]
1
  • 1
    Use an associative array whose key is the color. Commented Nov 7, 2014 at 16:48

1 Answer 1

2

Make the result array an associative array keyed by the color.

$people_by_color = array();
foreach ($people as $person) {
    if (isset($people_by_color[$person['color']])) {
        $people_by_color[$person['color']]['name'] .= ', ' . $person['name'];
        $people_by_color[$person['color']]['color'] .= ', ' . $person['color'];
    } else {
        $people_by_color[$person['color']] = $person;
    }
}
$people_by_color = array_values($people_by_color); // Turn into indexed array
Sign up to request clarification or add additional context in comments.

1 Comment

This worked perfectly, thanks! BTW, you missed a parenthesis on the if statement. I removed the color line after the name because I don't really want to combine two values that are the same, I just figured it would combine them regardless if using array_merge_recursively.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.