php - 如何对 3 维数组中的值求和 [英] php - how to sum a value from 3 dimensional array
问题描述
我有如下数据:
Array
(
[1] => Array
(
[A] => Array
(
[AA] => 3
[AB] => 5
)
[B] => Array
(
[BA] => 2
)
[2] => Array
(
[C] => Array
(
[CA] => 4
)
[D] => Array
(
[DA] => 1
[DB] => 2
)
)
[3] => Array
(
[E] => Array
(
[EA] => 1
[EB] => 2
[EC] => 3
)
[F] => Array
(
[FA] => 0
[FB] => 7
[FC] => 7
)
)
我想对价值求和,这是我的期望:
I want to sum the value and this is my expectation :
Array(
[1] => 10
[2] => 7
[3] => 20
)
这是我用来对值求和的代码:
Here is my code that I used for summing the value :
$total[$country_id][$province_id][$city_id] = $amount;
$result = array();
foreach( $total as $key => $val ){
$total[$key] = array_sum ( $val );
}
有人可以解释我的代码有什么问题或解释 foreach 是如何工作的吗?因为我的代码的结果是 0,实际上我只研究了大约 1 周的 foreach.谢谢
can someone explain what is wrong with my code or explain how foreach work? because the result of my code is 0 and actually I just studied around 1 week about foreach. Thanks
推荐答案
如果你想了解更多关于 foreach
的信息,这里有一个更详细的解决方案:
As you want to know more about foreach
, here is a more verbose solution using it :
$total = 0;
$totalByCountry = [];
// iterate over each country
foreach ($arr as $countryId => $provinces) {
$totalByCountry[$countryId] = 0;
// iterate over each province
foreach ($provinces as $provinceId => $cities) {
// iterate over each city
foreach ($cities as $cityId => $value) {
$totalByCountry[$countryId] += $value;
$total += $value;
}
}
}
var_dump(totalByCountry)
的结果:
array (size=3)
1 => int 10
2 => int 7
3 => int 20
var_dump($total)
的结果:
int 37
-- 编辑 --
在现实世界的项目中,你最好不要那么冗长,并使用为这种情况制作的 php 函数,例如 array_walk_recursive(),如 Philipp Maurer 和 Firoz Ahmad 答案.
In real world project, you better be less verbose and use php functions made for this kind of situation like array_walk_recursive(), as in Philipp Maurer and Firoz Ahmad answers.
这篇关于php - 如何对 3 维数组中的值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!