我有一个包含以下数组$menu_choice_in
的多维数组:
array(5) {
[0]=>
array(1) {
[0]=>
array(1) {
["additional_price"]=>
string(3) "1.2"
}
}
[1]=>
array(2) {
[0]=>
array(1) {
["additional_price"]=>
string(3) "1.2"
}
[1]=>
array(1) {
["additional_price"]=>
string(3) "1.2"
}
}
[2]=>
array(2) {
[0]=>
array(1) {
["additional_price"]=>
string(1) "1"
}
[1]=>
array(1) {
["additional_price"]=>
string(1) "2"
}
}
[3]=>
array(2) {
[0]=>
array(1) {
["additional_price"]=>
string(3) "2.1"
}
[1]=>
array(1) {
["additional_price"]=>
string(3) "2.8"
}
}
[4]=>
array(0) {
}
}
我想尝试sum
additional_price
并且应该将其返回到多维数组中,如下所示:
array(5) {
[0]=>
array(1) {
["additional_price"]=>
string(3) "1.2"
}
[1]=>
array(1) {
["additional_price"]=>
string(3) "2.4"
}
[2]=>
array(1) {
["additional_price"]=>
string(1) "3"
}
[3]=>
array(1) {
["additional_price"]=>
string(3) "4.9"
}
[4]=>
array(1) {
["additional_price"]=>
string(3) "0"
}
}
你可以帮帮我吗?谢谢(:
答案 0 :(得分:2)
使用array_walk
,array_sum
和array_column
(自PHP 5.5起可用)功能的简短解决方案:
$result = [];
array_walk($menu_choice_in, function($v) use(&$result){
$prices = array_column($v, "additional_price");
$result[] = ["additional_price" => array_sum($prices)];
});
print_r($result);
答案 1 :(得分:0)
这应该有用......
$sum_additional_price = array();
foreach ($menu_choice_in as $subarray) {
$additional_price = 0.0;
foreach ($subarray as $subsubarray) {
$additional_price += floatval($subsubarray['additional_price']);
$sum_additional_price[] = array('additional_price' => (string)$additional_price);
}