从多维数组中获取值的总和

时间:2015-07-07 16:41:15

标签: php arrays multidimensional-array

我真的需要帮助来获取我的数组的值的总和,我已经尝试研究如何解决这个但我最终得到错误,如使用array_sum()但最终在array_sum期望1参数是数组,并尝试$ value3 + = $ value3并得到一个结果但不正确,顺便说一下这里是我的代码:

var_export($_POST['guests']);
echo "<br />";
foreach($_POST['guests'] As $key1 => $value1){
    foreach($value1 As $key2 => $value2){
        foreach($value2 As $value3){

        }

    }
    echo "Room Type: " . $key1 . " No. of Rooms: " . $key2 . " No. of Guest: " . array_sum($value3) . "<br /> ";

}

以下是此结果:

array ( 1 => array ( 2 => array ( 0 => '1', 1 => '2', ), ), 2 => array ( 1 => array ( 0 => '4', ), ), )
  

警告:array_sum()期望参数1为数组,字符串在第14行的C:\ xampp \ htdocs \ nation \ reservation-form3.php中给出   房间类型:1房间数量:2客人数量:

     

警告:array_sum()期望参数1为数组,字符串在第14行的C:\ xampp \ htdocs \ nation \ reservation-form3.php中给出   房间类型:2房间数量:1客人数量:

3 个答案:

答案 0 :(得分:3)

使用PHP的RecursiveArrayIteraorRecursiveIteratorIterator类,

$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($input));
$sum = array_sum(iterator_to_array($it, false));
  

重要:请注意,iterator_to_array()中的第二个参数是false,这意味着在将递归迭代器转换为数组时不要使用数组&#39 ; s默认键&#39;。如果将其设置为true(默认情况下始终为默认值),则包含具有相同键的成员的子数组将覆盖生成数组的成员,您将看到意外结果。

如果您将显示的数组作为$input提供给此,$sum将为7

答案 1 :(得分:2)

这应该适合你:

使用array_walk_recursive()循环遍历所有数组值,然后将其添加到您的总和中,例如

$sum = 0;
array_walk_recursive($array,function($v, $k)use(&$sum){
    $sum += $v;
});

echo $sum;

因此,您甚至不必担心阵列的深度。

答案 2 :(得分:1)

我想你想要这样

   $_POST['guests'] = array ( 
   // RoomType => ( RoomNum => ( GuestList 
   // though i don't understand why guests in room are array
   // But no. of room can't be zero :) 
   1 => array ( 2 => array ( 0 => '1', 1 => '2', ), ), 
   2 => array ( 1 => array ( 0 => '4', ), ), );

echo "<br />";
foreach($_POST['guests'] As $key1 => $value1)          // Loop with RoomType
    foreach($value1 As $key2 => $value2)      // Loop with RoomNum
      echo "Room Type: " . $key1 . 
           " No. of Rooms: " . $key2 . 
           " No. of Guest: " . array_sum($value2) . "<br />";

结果

<br />
Room Type: 1 No. of Rooms: 2 No. of Guest: 3<br />
Room Type: 2 No. of Rooms: 1 No. of Guest: 4<br />