I am trying to get the total sum of this array:
Array
(
[1] => 0
[2] => 1
[3] => Array
(
[0] => 1
[1] => 1
[2] => 1
)
[4] => 1
[5] => 0
)
In this case the sum should be 5. I can't seem to get it to work. Can someone help me?
EDIT:
I have tried using array_sum (which obviously doesn't work) and a recursive array like this:
$array_obj = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
$sum = 0;
foreach($array_obj as $key => $value) {
if($key == '3')
$sum += $value;
}
Somehow this returns 20;
You can use array_walk_recursive()
in combination with using an outer variable by reference:
$sum = 0;
array_walk_recursive($array, function($number) use (&$sum) {
$sum += $number;
});
echo $sum;
In case an element of an array is an array itself, array_walk_recursive()
will iterate through it. Otherwise it will call the function on the element.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加