sum values in sub array

188 views Asked by At

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

...

2

There are 2 answers

0
gingerCodeNinja On BEST ANSWER

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

1
NautMeg On

I could be wrong but this looks like PHP to me. In which case I would probably just use objects as follows:

<?

class className {
    public $name;
    public $hours;
}

$name1 = new className();
$name1->name = "name1";
$name1->hours = array(1, 12, 10);

$name2 = new className();
$name2->name = "name2";
$name2->hours = array(0.25, 0.55, 0.35, 5);

$names = array($name1, $name2);

foreach ($names as $name){
    $sum_name = 0.00;
    foreach ($name->hours as $value){
        $sum_name = $sum_name + $value;
    }
    echo($sum_name . " hours " . $name->name);
    echo("<br>");
}
?>