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