我想計算一個從底部到頂部結轉的值。如何使用PHP從下到上遞歸計算?
例如從上面的圖像,我有這樣的狀態A,B,C,d,文萊國家下Ë各自具有的6,4,4,3,3等級值。
要計算值,我需要加上所有的值併除以狀態數。
(6 + 4 + 4 + 3 + 3)/ 5 = 4
只能在狀態電平,計算後它將被被彈出到他的父母,由求和併除以該評級值孩子的數量。
我目前的解決方案使用嵌套for循環,但它只適用於我知道層次結構的確切深度。因此,如果我添加WORLD成爲PLANET的子項,我需要手動添加另一個嵌套的for循環來計算評分,這不是很優雅。我期待將當前的解決方案轉換爲更具動態性的解決方案。
空白功能:
function getRating($place_id){
//do other things
//get ratings from all states in the country, summed and divide by the number of states
//return result of average rating
}
$world_id = 1;
$asia_id = 3;
$brunei_id = 7;
getRating($world_id);
//expected result : 5
getRating($asia_id);
//expected result : 4
getRating($brunei_id);
//expected result : 4
目前的解決方案:
//calculate continent rating
foreach ($subcontinents as $key => $subcontinent) {
//calculate sub-continent rating
foreach ($countries as $key => $country) {
//calculate country ratings
$rating_count = sizeof($state_ratings);
$total_country_achievement = 0;
foreach ($state_ratings as $key => $state_rating) {
$total_rating_achievement = 0;
$state_achievement = $state_rating->value;
$total_rating_achievement = $total_rating_achievement + $state_achievement;
}
$total_country_achievement = $total_rating_achievement/$rating_count;
}
}
你可以添加輸入數據的'var_dump()'?爲什麼你的內部循環中有一個硬編碼的變量值? – jeroen
@jeroen hi harcode只是想說明額定值,對於var_dump()實際上我可以使用上面的示例解決方案獲得我想要的值,但它不是很優雅,因爲如果需要手動添加另一個for循環其他父母是否存在 –
您的期望值是多少?您是在尋找特定國家的$ total_country_achievement,還是尋找所有國家價值的數組,或者您只是追求世界價值或整個樹? –