1 回答
TA贡献1789条经验 获得超10个赞
你需要超过 1 个 foreach。每次最深的迭代检查是否添加了服务。如果是,则添加当前值,如果不是,则添加整个服务。最后加入当前数组。
function count_services($array)
{
$service_list = [];
foreach ($array as $row) {
foreach ($row['services'] as $service) {
if (isset($service_list[$service['service_id']])) {
$service_list[$service['service_id']]['service_total'] += $service['service_total'];
} else {
$service_list[$service['service_id']] = $service;
}
}
}
return [
'group_description' => 'Total',
'services' => array_values($service_list)];
}
print_r(count_services($array));
输出:
Array
(
[group_description] => Total
[services] => Array
(
[0] => Array
(
[service_id] => 1
[service_name] => Security
[service_total] => 16
)
[1] => Array
(
[service_id] => 4
[service_name] => Catering
[service_total] => 35
)
[2] => Array
(
[service_id] => 5
[service_name] => Lighting
[service_total] => 8
)
)
)
- 1 回答
- 0 关注
- 104 浏览
添加回答
举报