Getting the sum of values ​​from a multidimensional array

I really need help in getting the sum of the values ​​of my array, I already tried to investigate how to solve this, but in the end I get errors, as when using array_sum (), but in the end in array_sum it is expected that 1 parameter will be an array and tried $ value3 + = $ value3 and had a result, but not correct, by the way here is my code:

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 /> ";

}

and here is the result of this:

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

Warning: array_sum () expects parameter 1 to be an array, the line specified in C: \ xampp \ htdocs \ nation \ reservation-form3.php on line 14 Room Type: 1 Number of Rooms: 2 Number of Guests:

Warning: array_sum () expects parameter 1 to be an array, the line specified in C: \ xampp \ htdocs \ nation \ reservation-form3.php on line 14 Room Type: 2 Number of Rooms: 1 Number of Guests:

+4
3

,

   $_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 />
+1

PHP RecursiveArrayIteraor RecursiveIteratorIterator,

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

. , iterator_to_array() false, " ". true ( ), , , , .

$input, $sum 7.

+3

:

array_walk_recursive(), , .

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

echo $sum;

, .

+2

All Articles