如何使用PHP从底部到顶部递归计算?

时间:2017-10-05 08:56:49

标签: php recursion tree

我想计算一个从底部到顶部结转的值。

enter image description here

例如,根据上图,我在文莱国家拥有A,B,C,D,E国家,每个国家的评级值为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;

               }            

          }

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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