2014-12-18 2 views
0

재귀 함수에 문제가 있습니다. 나 좀 도와 줄 수 있겠 니? 아래 내 기능 :php | 재귀가있는 버그

function showTree($items, $level = 0) { 

      $arr = []; 

      foreach ($items as $item) { 
       $arr[] = str_repeat(":", $level * 2) . $item['name'] . "<br />"; 
       if (!empty($item['children'][0])) { 
        $level++; 
        $arr[] = $this->showTree($item['children'], $level); 
       } 
      } 

      return $arr; 
} 

그리고이 출력을 생성합니다

Array 
(
    [0] => Category1 

    [1] => Array 
     (
      [0] => ::SubCategory2 

      [1] => ::SubCategory1 

      [2] => Array 
       (
        [0] => ::::SubSubCategory 

       ) 

     ) 

) 

을하지만 내 출력으로 조금 다른 데이터가 필요

Array 
    (
     [0] => Category1 
     [1] => ::SubCategory2 
     [2] => ::SubCategory1 
     [3] => ::::SubSubCategory 

    ) 

내 실수 어디에 있습니까? 감사!

P> S :

입력 :

Array 
(
    [0] => Array 
     (
      [id] => 1 
      [name] => Category1 
      [parent] => 0 
      [children] => Array 
       (
        [0] => Array 
         (
          [id] => 4 
          [name] => SubCategory2 
          [parent] => 1 
          [children] => Array 
           (
           ) 

         ) 

        [1] => Array 
         (
          [id] => 2 
          [name] => SubCategory1 
          [parent] => 1 
          [children] => Array 
           (
            [0] => Array 
             (
              [id] => 3 
              [name] => SubSubCategory 
              [parent] => 2 
              [children] => Array 
               (
               ) 

             ) 

           ) 

         ) 

       ) 

     ) 
) 
+0

레벨을 아무데도 줄이지 않았습니다. 제발, 당신의 입력 배열은 다른 사람들에게 보여주세요. – vaso123

+0

준비. 질문에 데이터를 입력하십시오. – user889349

답변

1

변경이 라인 :

$arr[] = $this->showTree($item['children'], $level); 

에 :

$arr = array_merge($arr, $this->showTree($item['children'], $level)); 

e.e. 현재의 배열에 새로운 값으로서 아이를 이동 중으로 돌려 주어지는 배열을 추가하지 않고, 현재의 배열에 값을 추가합니다.

+0

감사합니다 !!!!! 그것은 작동합니다! – user889349

+0

이 방법으로도 할 수 있지만,'array_merge'를 사용하면 입력이 매우 커질 경우 상당한 성능 영향을 미칠 수 있습니다 (즉, 매우 느려질 수 있음). – AlpineCoder

0

이 시도 :

function showTree($items, $level = 0, &$arr = array()) { 

     foreach ($items as $item) { 
      $arr[] = str_repeat(":", $level * 2) . $item['name'] . "<br />"; 
      if (!empty($item['children'][0])) { 
       $level++; 
       $this->showTree($item['children'], $level, $arr); 
      } 
     } 

     return $arr; 
}