嗨,我有這個示例數組。我想計算總面積,然後將其加到父母總數加上地點的個人總數。所以第一個地點的總數將是「11」,因爲7 + 4。那麼「國家」父母也會這樣做10(第一個國家父母)+11(第一個孩子)+10(第二個孩子)= 31.PHP計算嵌套數組總數
$arr = array(
array(
'type' => 'state', 'total' => '10',
'location' => array(
array(
'type' => 'location', 'total' => '4',
'area' => array(
array('type' => 'area', 'total' => '6'),
array('type' => 'area', 'total' => '1')
)
),
array(
'type' => 'location', 'total' => '5',
'area' => array(
array('type' => 'area', 'total' => '2'),
array('type' => 'area', 'total' => '3')
)
)
)
),
array(
'type' => 'state', 'total' => '20',
'location' => array(
array(
'type' => 'location', 'total' => '4',
'area' => array(
array('type' => 'area', 'total' => '8'),
array('type' => 'area', 'total' => '7')
)
)
)
)
);
所需的正確的輸出現在應該重新創建:
$arr_FINAL = array(
array(
'type' => 'state', 'total' => '31',
'location' => array(
array(
'type' => 'location', 'total' => '11',
'area' => array(
array('type' => 'area', 'total' => '6'),
array('type' => 'area', 'total' => '1')
)
),
array(
'type' => 'location', 'total' => '10',
'area' => array(
array('type' => 'area', 'total' => '2'),
array('type' => 'area', 'total' => '3')
)
)
)
),
array(
'type' => 'state', 'total' => '39',
'location' => array(
array(
'type' => 'location', 'total' => '19',
'area' => array(
array('type' => 'area', 'total' => '8'),
array('type' => 'area', 'total' => '7')
)
)
)
)
);
在持續未完成的解決方案爲每CBroe要求:
// country > state > location > area
foreach ($arr as $k => $v) {
foreach ($v['location'] as $k2 => $v2) {
foreach ($v2['area'] as $k3 => $v3) {
echo $v3['total'] . ",";
$ctr_area[] = $v3['total'];
}
$arr2[$k]['location'][$k2]['total'] += array_sum($ctr_area);
$ctr_location[] = $v2['total'];
$ctr_area = array();
}
$arr2[$k]['total'] += array_sum($ctr_location);
$ctr_state[] = $v['total'];
$ctr_location = array();
}
這是數據的一個非常具體的設置,可能會需要特定的功能。我不會浪費時間和精力制定動態解決方案。首先讓它工作,然後讓它變得更好。 – DarkMukke
所以,你只是在這裏放棄你的要求,甚至沒有表現出絲毫的方法...是,「你挑戰複雜的邏輯問題的激情」 - 你談論你的個人資料? – CBroe
@CBroe我是多任務處理。我發佈了這個問題,然後繼續這樣做。我目前的解決方案到目前爲止是「檢查更新的問題」:) – marknt15