子数组中的总和值

sum values in sub array

这就是我将值存储到数组的方式

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

这是结果

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

)

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

)

我需要

这样的结果
echo $sum_of_first_array. "hours" .$name; 

或:

23 小时 name1

6.15 小时 name2

...

我可能是错的,但这看起来像 PHP。在这种情况下,我可能只使用如下对象:

<?

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

您可以通过 array_sum 使用 array_map

运行 您的价值观

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

总而言之,就像-


$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

https://www.tehplayground.com/paAkQ8riS5KwFSfP

虽然更好的解决方案是边走边添加这些,例如


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

}

print_r($array);

https://www.tehplayground.com/kA2QDWUluJ53Ueia