我有一个包含多个对象的 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"}]
使结果数组成为按颜色键控的关联数组。
$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