从PHP递归函数返回最后一组数组

时间:2018-08-05 13:40:59

标签: php arrays recursion

我正在尝试通过递归函数过滤数组集,但过滤完成后无法返回它。

function get_the_answer($number, $array=array()){
 $returnArray = array();
 $QS = array(1=>'C', 2=>'B', 3=>'C', 4=>'D');
 $SL = array(
           1 => array(
                    'cb1' => array('A','B', 'D'),
                    'cb2' => array('B','C', 'D'),
                    'cb3' => array('A','C', 'B'),
                ),

            2 => array(
                    'cb1' => array('B','C','D'),
                    'cb2' => array('A','C','D'),
                    'cb3' => array('A','B','D'),
                ),

            3 => array(
                    'cb1' => array('E','C','D'),
                    'cb2' => array('B','E','D'),
                    'cb3' => array('A','C','D'),
                ),
            4 => array(
                    'cb1' => array('A','D','E'),
                    'cb2' => array('A','C','D'),
                    'cb3' => array('B','C','D'),
            )
 ); 
 if($number<=4){ 
        if(empty($array)){
          $returnedValue = return_filtered_company($SL[$number], $QS[$number]);
        } else {
          $returnedValue = return_filtered_company($array, $QS[$number]);
        }

        //print_r($returnedValue); -> receiving values nicely, need the last set of array which is 'cb3'

        $returnArray[] = $returnedValue; 

        $increment = $number+1;
        if($increment<=4){
            $result=array_intersect_key($SL[$increment], $returnedValue);
             get_the_answer($increment, $result);
        }
    }
  return $returnArray;
}

//function for company calculation 
function return_filtered_company($companyArray, $answer){
 $foundCB=array();

 if(is_array($companyArray) && count($companyArray)){
    foreach ($companyArray as $name => $arrayVal){
        if (in_array($answer, $arrayVal)) {
            $foundCB[$name]=$name;
        }
    }
 }

return $foundCB;
}

我这样调用答案函数:

$ans = get_the_answer(1);
    echo '<pre>';
    print_r($ans);
    echo '</pre>';

一切正常,但返回的值是第一次递归而不是最后一次递归。答案应为 cb3

请有人帮忙找出什么是/是返回上一次递归的最佳解决方案。

1 个答案:

答案 0 :(得分:1)

替换第42行get_the_answer($ increment,$ result);与return get_the_answer($increment, $result);一起解决。

See the screenshot