Sum loops several arrays

5jvtdoz2  于 2022-10-22  发布在  PHP
关注(0)|答案(1)|浏览(123)

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

ha5z0ras

ha5z0ras1#

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;

相关问题