phpmultidimensional-arrayarray-sum

sum values in sub array


this is how I store values to array

$array[$row['name']][] = $row['from'] - $row['to'];

and here is result

Array
(
   [name1] => Array
    (
        [0] => 1
        [1] => 12
        [2] => 10
    )

)

Array
(
   [name2] => Array
    (
        [0] => 0.25
        [1] => 0.55
        [2] => 0.35
        [3] => 5
    )

)

i need result like

echo $sum_of_first_array. "hours" .$name; 

or:

23 hours name1

6.15 hours name2

...


Solution

  • You could run your values through array_sum using array_map

    $array = array_map('array_sum', $array);

    All in all, something like -

    
    $rows = [
        ['name' => 'name1', 'from' => 4, 'to' => 3],
        ['name' => 'name1', 'from' => 32, 'to' => 20],
        ['name' => 'name1', 'from' => 999, 'to' => 989],
        ['name' => 'name2', 'from' => 10.25, 'to' => 10],
        ['name' => 'name2', 'from' => 10.55, 'to' => 10],
        ['name' => 'name2', 'from' => 10.35, 'to' => 10],
        ['name' => 'name2', 'from' => 5, 'to' => 0],
    ];
    $array = [];
    foreach ($rows as $row) {
        $array[$row['name']][] = $row['from'] - $row['to'];    
    
    }
    
    print_r($array); // what you have so far
    
    $array = array_map('array_sum', $array);
    
    print_r($array); // what you want
    
    

    See https://www.tehplayground.com/paAkQ8riS5KwFSfP

    Although a better solution would be to add these as you go, like

    
    $array = [];
    foreach ($rows as $row) {
        $array[$row['name']] += $row['from'] - $row['to'];    
    
    }
    
    print_r($array);
    

    See https://www.tehplayground.com/kA2QDWUluJ53Ueia