這可能對你們中的一些人很簡單,但我真的在PHP中是虛擬的。我所需要的只是轉換一個多維數組並計算它的一些子數組值。PHP:按陣列計算數組值
Array
(
[0] => Array
(
[date] => 2014-10-30
[mission] => one
[point] => 10
)
[1] => Array
(
[date] => 2014-10-31
[mission] => five
[point] => 10
)
[2] => Array
(
[date] => 2014-11-19
[mission] => one
[point] => 8
)
和輸出會是這樣:
Array
(
[one] => Array
(
[mission] => one
[point] => 18 // sum all points where [mission] => one
[count] => 2
[everage] => 9 // 18/2
)
[five] => Array
(
[mission] => five
[point] => 10
[count] => 1
[everage] => 10
)
它是簡單的獲得使用foreach
[point]
值的總和,但麻煩開始的時候我試圖讓與同一[mission]
值陣列count
。這就是我的代碼:
foreach($missionsarray as $row) {
if(!isset($newarray[ $row['mission'] ])) {
$newarray[ $row['mission'] ] = $row;
$newarray[ $row['mission'] ]['count'] = count($row['point']);
continue ;
}
$newarray[ $row['mission'] ]['point'] += $row['point'];
}
print_r($newarray);