2017-10-05 47 views
0

我想計算一個從底部到頂部結轉的值。如何使用PHP從下到上遞歸計算?

enter image description here

例如從上面的圖像,我有這樣的狀態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; 

       }    

      } 
+1

你可以添加輸入數據的'var_dump()'?爲什麼你的內部循環中有一個硬編碼的變量值? – jeroen

+0

@jeroen hi harcode只是想說明額定值,對於var_dump()實際上我可以使用上面的示例解決方案獲得我想要的值,但它不是很優雅,因爲如果需要手動添加另一個for循環其他父母是否存在 –

+0

您的期望值是多少?您是在尋找特定國家的$ total_country_achievement,還是尋找所有國家價值的數組,或者您只是追求世界價值或整個樹? –

回答

0

你應該做一個遞歸函數來遍歷樹,計算每個級別的平均值。像這樣的東西(適應你自己的需要)。

function getValueOfLeaf($node) { 
    if (is_array($node)) { 
     $sum = 0; 
     foreach ($node as $key => $value) { 
      $sum += getValueOfLeaf($value); 
     } 
     return $sum/sizeof($node); 
    } else { // not an array 
     return (int) $node; 
    } 
} 

爲了得到一個國家的值或大陸值,這樣做:

getValueOfLeaf($planet['earth']['asia']['south-east-asia']['brunei']; // get brunei states average 
getValueOfLeaf($planet['earth']['europe']); // get average value of all country averages in Europe 
getValueOfLeaf($planet['earth']); // get average for earth 
0

讓你發揮遞歸這樣

<?php 
    $arr = [ 
     5, 
     [[10,[6,4,4,3,3],5,5],4,2], 
     6 
    ]; 
    function getAvg($arr){ 
     foreach ($arr as $key => &$value) { 
      if(is_array($value)){ 
       $value = getAvg($value); 
      } 
     } 
     $avg = array_sum($arr)/count($arr); 
     echo "\nAverage of : ".implode(", ", $arr)." => ".$avg; 
     return $avg; 
    } 
    $avg = getAvg($arr); 
    echo "\nAverage of all is : ".$avg; 
?> 

現場演示:https://eval.in/874201

+0

嗨,也許我誤解你的代碼,但只有價值6,4,4,3,3是確切的評級,其他人是從這個價值的平均值,並繼續上面,並繼續爲每個孩子的平均值 –

+0

@NediSidi:是的是你繪製的精確數組形式 – C2486

+0

@NediSidi:或者分享你的php數組數據樣本? – C2486