2017-10-05 45 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