-1

I don't know how I can get the sum

array(1) { 
    [0]=> array(1) { 
        ["Dato1"]=> string(6) "714084" 
    } 
    [1]=> array(1) { 
        ["Dato2"]=> string(6) "600397" 
    } 
}

 array(2) { 
    [0]=> array(1) { 
        ["Dato1"]=> string(6) "714084" 
    } 
    [1]=> array(1) { 
        ["Dato2"]=> string(6) "600397" 
    } 
}

The idea is:

sum: 25+125+95 = 245

sum: 32+52+57 = 141

<?php
$sum=0;

$suma =0;
$iterator = new MultipleIterator;
$iterator->attachIterator(new ArrayIterator($datoscaser));
$iterator->attachIterator(new ArrayIterator($datosmapfre));
$iterator->attachIterator(new ArrayIterator($datosbbva));

foreach ($iterator as $values) {

}

            ?>

I have tried to do this:

foreach ($iterator as $values) {
$suma=$sum+$values;
}

but it tells me that it is an array

6
  • Start with var_dump($values). It's an array like [25, 125, 95], right? How do you sum an array of values? array_sum. Now just add that to $sum Commented Oct 21, 2022 at 9:23
  • See fixed demo onecompiler.com/php/3ykkgr7x9 Commented Oct 21, 2022 at 9:33
  • Does this answer your question? Summing of all elements in the sub array - PHP Commented Oct 21, 2022 at 9:34
  • This is the var_dump($values) array(3) { [0]=> array(1) { ["Dato1"]=> string(6) "714084" } [1]=> array(1) { ["Dato2"]=> string(6) "372741" } [2]=> array(1) { ["Dato3"]=> string(6) "195867" } } array(3) { [0]=> array(1) { ["Dato1"]=> string(6) "600397" } [1]=> array(1) { ["Dato2"]=> string(6) "-37872" } [2]=> array(1) { ["Dato3"]=> string(5) "97276" } } Commented Oct 21, 2022 at 9:35
  • foreach ($iterator as $values) { $sum += array_sum($values); } echo $sum; The result $sum is "0" Commented Oct 21, 2022 at 9:37

1 Answer 1

2

you can use :

$a = [
    ["Dato1"=> "714084"],
    ["Dato2"=> "600397"]
];

function sum($carry, $item)
{
    return $carry += array_values($item)[0];
}

var_dump(array_reduce($a, "sum"));

if you want something more flexible :

<?php

$a = [
    ["Dato1"=> "714084"],
    ["Dato2"=> "600397"],
    14
];


$total = 0;

//Does not persist
array_walk_recursive( $a, function($value, $key) use (&$total) {
    return $total += (int)$value;
}, $total);

echo $total;
Sign up to request clarification or add additional context in comments.

3 Comments

for $iterator tell me: Found 'MultipleIterator'
You don't need to use MultipleIterator use PHP native function
But I don't understand how to insert that in what I need, because I have to go through the three arrays and add each of them separately

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.