PHP - 组合具有相同键值的数组

时间:2014-11-07 16:45:05

标签: php arrays json object merge

我有一个包含多个对象的JSON数组,这里有一个例子:

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

我使用json_decode($people, true)将它们转换为数组...

现在让我们说我希望将具有相同color的那些组合起来。我必须array_merge_recursive($people[0], $people[1]),因为他们都green作为color。请注意,我必须指定要递归合并的那些。

在将$people解码为数组格式并自动合并具有相同键值的那些之后,我如何遍历foreach($people as $person) { // If a person has same color of previous // person then merge them recursively. }

这样的事情:

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

所以我可以在循环后得到这个:

{{1}}

1 个答案:

答案 0 :(得分:2)

使结果数组成为一个由颜色键控的关联数组。

$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