0

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

$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 小时名称1

6.15 小时名称2

...

4

2 回答 2

0

我可能是错的,但这对我来说就像 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>");
}
?>
于 2020-02-17T18:03:53.273 回答
0

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

于 2020-02-17T18:13:23.190 回答