如何使用多维数组计算数据

时间:2016-07-13 07:05:14

标签: php arrays multidimensional-array

我有一个包含以下数组$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"
  }
}
你可以帮帮我吗?谢谢(:

2 个答案:

答案 0 :(得分:2)

使用array_walkarray_sumarray_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);
}