0

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

...

1

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

Comments

0

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>");
}
?>

1 Comment

yes it is php. But there can by much more $names than 2. it is result from DB. I just need to total sum of difference betwen values (from-to) with same name. like: i have values in DB: name1(from-to), name1(from-to), name2(from-to), name2(from-to), name2(from-to). Then I need sum of name1(from-to) and sum of name2(from-to)

Your Answer

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