2015-04-03 153 views
0

我面對這種挑戰:顯示分層,多維陣列作爲嵌套列表(遞歸)

我需要從一個分層的,多維陣列作爲嵌套列表顯示數據。我想使用遞歸來做到這一點,因爲我不知道列表可能有多少級別。這是我工作中的數據(簡化):

array (size=54) 
    0 => 
    object(stdClass)[786] 
     public 'term_id' => string '1' (length=3) 
     public 'name' => string 'All' (length=25) 
     public 'parent' => string '0' (length=3) 
     public 'children' => array (size=2) 
      0 => 
       object(stdClass)[785] 
        public 'term_id' => string '2' (length=3) 
        public 'name' => string 'Clothes' (length=25) 
        public 'parent' => string '1' (length=3) 
        public 'children' => (size=1) 
         0 => 
         object(stdClass)[786] 
          public 'term_id' => string '3' (length=3) 
          public 'name' => string 'Scarves' (length=25) 
          public 'parent' => string '2' (length=3) 
      1 => 
       object(stdClass)[785] 
        public 'term_id' => string '4' (length=3) 
        public 'name' => string 'Gloves' (length=25) 
        public 'parent' => string '1' (length=3) 

結果應該是一個嵌套列表類似於此:

  • 所有
    • 衣服
      • 圍巾
    • 食品
      • 蔬菜

嘗試許多時間後,我已經建立了利用array_walk_recursive和我自己的另一遞歸函數(簡體):

function attachChildren($items) 
{ 
    foreach($items as $item) { 
     echo $item->name; 
     if (is_array(($item->children))) { 
      $this->attachChildren($item->children); 
     } 
    } 
} 

function buildTree($value, $key) 
{ 
    echo $value->name; 
    if (is_array($value->children)) { 
     $this->attachChildren($value->children); 
    }   
} 

array_walk_recursive($sortedArray, 'buildTree'); 

這個解決方案的問題正在獲取格式化權限。兩個函數產生輸出,我發現很難將項目排列在縮進列表中。

將此數組顯示爲具有多個級別的縮進列表的最佳方法是什麼?

+0

遍歷數組和子數組。第一個索引元素'ul'子數組''li'子數組追加'ul> li' – Bsienn 2015-04-03 11:54:27

回答

0
function walk($array){ 
    foreach ($array as $key => $value) { 
     echo "<ul>"; 
     if(is_array($value)){ 
      echo "<li>{$value['name']}</li>"; 

      walk($value); 
     } 
     echo "</ul>"; 
    } 
} 

$ar = [ 
     ['name' => 'All', ['name' => 'Clothes', ['name' =>'Scarves']]], 
     ['name' => 'Gloves'] 
     ]; 

walk($ar);