1 回答

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個贊
你需要超過 1 個 foreach。每次最深的迭代檢查是否添加了服務(wù)。如果是,則添加當(dāng)前值,如果不是,則添加整個服務(wù)。最后加入當(dāng)前數(shù)組。
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 關(guān)注
- 134 瀏覽
添加回答
舉報