2016-06-17 51 views
0

我試圖通過遞歸函數將php數組格式化爲可視化樹,但由於某種原因它似乎無法工作。它只打印第一層。這是我的代碼。PHP Array到菜單樹

function recursiveMenu($arr){ 
    $maketree = ""; 
    if(is_array($arr)){ 
     foreach($arr as $key => $val){ 
      if(is_array($val)){ 
       $maketree .= "<div class='expcol jexpand'><a>[-]</a>".$key."</div>" 
          . "<div class='section jsection'>"; 
       recursiveMenu($val); 
      }else{ 
       $maketree .= "<div>".TB.TB." <a href='index.php?action=". $val . "' >" 
          . "<div class='menuitem'>" . $val . "</div>" 
          . "</a></div>"; 
      } 
      $maketree .="</div>"; 
     } 
    } 
    return $maketree; 
} 

function makeMenu($srch) { 
    $makemenu = "<div>"; 
    $makemenu .= recursiveMenu($srch); 
    $makemenu .= "</div>"; // </a> 
    return $makemenu; 
} 

下面是我的數組從DB導致:

$srch = Array(
    [Asia] => Array(
      [South] => Array(
        [India] => Array(
          [0] => Mumbai 
          [1] => New Delhi 
          [2] => Chennai 
         ) 
       ) 
     ) 

    [Europe] => Array(
      [West] => Array(
        [Spain] => Array(
          [0] => Madrid 
         ) 
       ) 

      [North] => Array(
        [Denmark] => Array(
          [0] => Copenhagen 
         ) 
       ) 
     ) 

    [Americas] => Array(
      [South] => Array(
        [Brazil] => Array(
          [0] => Brasilia 
         ) 
       ) 

      [North] => Array(
        [USA] => Array(
          [0] => Los Angeles 
          [1] => Atlanta 
          [2] => Boston 
          [3] => Houston 
         ) 
       ) 

      [Central] => Array(
        [Mexico] => Array(
          [0] => Cancun 
          [1] => Mexico city 
         ) 
       ) 

     ) 

    [Africa] => Array(
      [South] => Array(
        [South Africa] => Array(
          [0] => Cape Town 
          [1] => Johannesburg 
         ) 
       ) 
     ) 
) 

實際結果我得到這個是(僅第一級):

[-]Asia 
[-]Europe 
[-]Americas 
[-]Africa 

有誰看到有什麼不對嗎?提前致謝。

回答

1

你是不是忘記將第二次遞歸調用的結果追加到recursiveMenu()到輸出中。我認爲你需要將第8行改爲:

$maketree .= recursiveMenu($val); 
+0

太棒了。這工作!謝謝。 – Ravi