子数组值的总和
Sum of subarray values
Array
(
[1~course2 20:00] => Array
(
[0] => Array
(
[pid] => 30
[anz_tn] => 6
)
[1] => Array
(
[pid] => 30
[anz_tn] => 4
)
[2] => Array
(
[pid] => 30
[anz_tn] => 5
)
)
[2~Course2 08:30] => Array
(
[0] => Array
(
[pid] => 30
[anz_tn] => 5
)
[1] => Array
(
[pid] => 11
)
[2] => Array
(
[anz_tn] => 4
)
)
.....
如何获得每个子数组的所有 "anz_tn" 的总和? (所有 [0]['anz_tn']、[1]['anz_tn'] 等的总和。)
我试过使用 $all[][$i]['anz_tn'] 但失败了。 ($all 是主数组,$i 是子数组的计数)。有没有办法使用 array_sum?
谢谢!
请这样尝试,
$sumArray = array();
foreach ($myArray as $k=>$subArray) {
foreach ($subArray as $id=>$value) {
if ($id == 'anz_tn')
$sumArray[$id]+=$value;
}
}
print_r($sumArray);
谢谢你,Manadh!
这为我指明了正确的方向。缺了一层数组(导致'unsupported operand error'),所以最后我想出了这个:
$sumArray = array();
foreach ($groupasweek as $s1k=>$s1v) {
foreach ($s1v as $s2k=>$s2v) {
foreach ($s2v as $id=>$value) {
if ($id == 'anz_tn') {
$sumArray[$s1k][$id] += $value;
}
}
}
}
顺便说一句,我在哪里可以接受答案?
Array
(
[1~course2 20:00] => Array
(
[0] => Array
(
[pid] => 30
[anz_tn] => 6
)
[1] => Array
(
[pid] => 30
[anz_tn] => 4
)
[2] => Array
(
[pid] => 30
[anz_tn] => 5
)
)
[2~Course2 08:30] => Array
(
[0] => Array
(
[pid] => 30
[anz_tn] => 5
)
[1] => Array
(
[pid] => 11
)
[2] => Array
(
[anz_tn] => 4
)
)
.....
如何获得每个子数组的所有 "anz_tn" 的总和? (所有 [0]['anz_tn']、[1]['anz_tn'] 等的总和。)
我试过使用 $all[][$i]['anz_tn'] 但失败了。 ($all 是主数组,$i 是子数组的计数)。有没有办法使用 array_sum?
谢谢!
请这样尝试,
$sumArray = array();
foreach ($myArray as $k=>$subArray) {
foreach ($subArray as $id=>$value) {
if ($id == 'anz_tn')
$sumArray[$id]+=$value;
}
}
print_r($sumArray);
谢谢你,Manadh!
这为我指明了正确的方向。缺了一层数组(导致'unsupported operand error'),所以最后我想出了这个:
$sumArray = array();
foreach ($groupasweek as $s1k=>$s1v) {
foreach ($s1v as $s2k=>$s2v) {
foreach ($s2v as $id=>$value) {
if ($id == 'anz_tn') {
$sumArray[$s1k][$id] += $value;
}
}
}
}
顺便说一句,我在哪里可以接受答案?