我有以下数组
Array
(
[0] => Array
(
[group_description] => Group 1
[services] => Array
(
[0] => Array
(
[service_id] => 1
[service_name] => Security
[service_total] => 10
)
[1] => Array
(
[service_id] => 4
[service_name] => Catering
[service_total] => 20
)
)
)
[1] => Array
(
[group_description] => Group 2
[services] => Array
(
[0] => Array
(
[service_id] => 1
[service_name] => Security
[service_total] => 6
)
[1] => Array
(
[service_id] => 4
[service_name] => Catering
[service_total] => 15
)
[2] => Array
(
[service_id] => 5
[service_name] => Lighting
[service_total] => 8
)
)
)
)
我想将具有相同服务的数组相加,然后创建一个总数组,并将其放回数组中,就像这样。
Array
(
[0] => Array
(
[group_description] => Group 1
[services] => Array
(
[0] => Array
(
[service_id] => 1
[service_name] => Security
[service_total] => 10
)
[1] => Array
(
[service_id] => 4
[service_name] => Catering
[service_total] => 20
)
)
)
[1] => Array
(
[group_description] => Group 2
[services] => Array
(
[0] => Array
(
[service_id] => 1
[service_name] => Security
[service_total] => 6
)
[1] => Array
(
[service_id] => 4
[service_name] => Catering
[service_total] => 15
)
[2] => Array
(
[service_id] => 5
[service_name] => Lighting
[service_total] => 8
)
)
)
[3] => 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
)
)
)
)
我试过循环数组,并在循环的同时创建一个新的数组,我使用了foreach循环,然后使用array_search函数查看我正在忙的数组并追加到新的数组。我使用了一个foreach循环,然后使用array_search函数来查看我正在忙的数组,并追加到新的数组中,但这并没有达到我想要的目的,我总是以相同的数组结束。就像我真的陷入了一个循环。我看过很多例子,但我觉得我的情况和例子并不相似。
foreach ($array as $value) {
if(array_search($value['service_id], array_column($array, 'service_id')) !== false) {
$newArray['service_id'] = $value['service_id'];
$newArray['service_name'] = $value['service_name'];
$newArray['service_total'] = $value['service_total'] + $newArray['service_total'];
} else{
$newArray[] = $value;
}
}
你需要超过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
)
)
)