我在php数组中有很多对象,如示例所示。我想获得一个新的类似对象,其中包含所有对象的所有唯一属性,如果找到相同的属性,则将添加和对象的该属性内的数量的值。
例如:
$data = array({"Browser": {
"Chrome": {
"amount": 1721
},
"Firefox": {
"amount": 121
}
},
"City": {
"USA": {
"amount": 2220
},
"China": {
"amount": 121
}
},
},
{"Browser": {
"UC Browser": {
"amount": 117
},
"Chrome": {
"amount": 40
}
},
"City": {
"USA": {
"amount": 212
},
"UK": {
"amount": 21
}
},
});
我想要得到的输出:
{
"Browser": {
"UC Browser": {
"amount": 117
},
"Chrome": {
"amount": 1761 //<=40 + 1721
},
"Firefox": {
"amount": 121
}
},
"City": {
"USA": {
"amount": 2432 //<= 1721 + 212
},
"UK": {
"amount": 21
},
"China": {
"amount": 121
}
},
}
类似地,数组内将有大约30个具有相同结构的相似对象。 我尝试了一个多星期,但无法解决这个问题。
答案 0 :(得分:0)
您可以通过创建一个递归函数来实现您的目标,该函数将对相同键的amount
个元素求和,如下所示:
function amount_sum_recursive(...$arrays) {
$result = [];
// iterate through $arrays as it can be more than 2 root elements in the $data array
foreach ($arrays as $array) {
foreach ($array as $key => $value) {
if (is_array($value)) {
// if the $value is an array - we need to go deeper
$result[$key] = amount_sum_recursive($result[$key] ?? [], $value);
} else {
// the $value is not an array - it's `amount` key:
// simply add current $value to the existing one in the $result array
$result[$key] += $value;
}
}
}
return $result;
}
测试:
$result = amount_sum_recursive(...$data);
echo json_encode($result, JSON_PRETTY_PRINT), PHP_EOL;
输出:
{
"Browser": {
"Chrome": {
"amount": 1761
},
"Firefox": {
"amount": 121
},
"UC Browser": {
"amount": 117
}
},
"City": {
"USA": {
"amount": 2432
},
"China": {
"amount": 121
},
"UK": {
"amount": 21
}
}
}