PHP - Combine arrays with same key value -
i have json array of multiple objects, here's example:
$people = [{"name":"john", "color":"green"}, {"name":"mary", "color":"green"}, {"name":"bob", "color":"red"}]
i utilize json_decode($people, true)
convert them array...
now let's want combine have same color
. i'd have array_merge_recursive($people[0], $people[1])
because both have green
color
. note have specify ones want merge recursively.
how can loop through $people
after it's been decoded array format , automatically merge recursively have same key value?
something this:
foreach($people $person) { // if person has same color of previous // person merge them recursively. }
so after looping:
[{"name":"john, mary", "color":"green, green"}, {"name":"bob", "color":"red"}]
make result array associative array keyed color.
$people_by_color = array(); foreach ($people $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 indexed array
php arrays json object merge
No comments:
Post a Comment