2011-11-05 73 views
5

我有這樣的陣列由SQL查詢返回的對象,其中top_id是我父ID字段:如何從對象的數組記錄集中獲取嵌套的HTML列表?

Array (
[0] => stdClass Object ([id] => 1 [top_id] => 0 [name] => Cat 1) 
[1] => stdClass Object ([id] => 2 [top_id] => 0 [name] => Cat 2) 
[2] => stdClass Object ([id] => 3 [top_id] => 0 [name] => Cat 3) 
[3] => stdClass Object ([id] => 4 [top_id] => 2 [name] => Subcat 1) 
[4] => stdClass Object ([id] => 5 [top_id] => 2 [name] => Subcat 2) 
[5] => stdClass Object ([id] => 6 [top_id] => 3 [name] => Subcat 3) 
[6] => stdClass Object ([id] => 7 [top_id] => 5 [name] => Subcat 4) 
) 

現在我需要獲得一個嵌套表像這樣使用PHP:

<ul> 
    <li>Cat 1</li> 
    <li>Cat 2 
    <ul> 
     <li>Subcat 1</li> 
     <li>Subcat 2 
     <ul> 
      <il>Subcat 3 
      <ul> 
       <li>Subcat 4</li> 
      </ul> 
      </li> 
     </ul> 
     </li> 
    </ul> 
    </li> 
    <li>Cat 3</li> 
</ul> 

任何想法? 由於

的所有映射對象
+0

「top_id」是否指示子類別屬於哪個類別? – TaylorOtwell

回答

9

首先到一個新的哈希(陣列),其中該索引是id

// map the array onto hash 
$hash = array(); 
foreach($array as $object) 
{ 
    $hash[$object->id] = array('object' => $object); 
} 

然後轉置該平坦散列成樹狀結構,請參閱本answer for another code example,它只是在這裏:

// build tree from hash 
$tree = array(); 
foreach($hash as $id => &$node) 
{ 
    if ($parent = $node['object']->top_id) 
     $hash[$parent]['children'][] =& $node; 
    else 
     $tree[] =& $node; 
} 
unset($node, $hash); 

最後,你可以輸出這個樹形結構爲HTML。這可以通過堆棧或遞歸來完成。這是一個變體與遞歸:

// render tree 
function render_tree($tree) 
{ 
    echo '<ul>', "\n"; 
    foreach($tree as $node) 
    { 
     render_node($node); 
    } 
    echo '</ul>'; 
} 

// render tree node 
function render_node($node, $level = 0) 
{ 
    $inset = str_repeat(' ', $level) . ' '; 
    echo $inset, '<li>', $node['object']->name; 
    if (isset($node['children'])) 
    { 
     echo "\n", $inset, ' <ul>', "\n"; 
     foreach($node['children'] as $node) 
     { 
      render_node($node, $level+1); 
     } 
     echo $inset, ' </ul>', "\n", $inset; 
    } 
    echo '</li>', "\n"; 
} 

// output 
render_tree($tree); 

輸出:

<ul> 
    <li>Cat 1</li> 
    <li>Cat 2 
    <ul> 
     <li>Subcat 1</li> 
     <li>Subcat 2 
     <ul> 
      <li>Subcat 4</li> 
     </ul> 
     </li> 
    </ul> 
    </li> 
    <li>Cat 3 
    <ul> 
     <li>Subcat 3</li> 
    </ul> 
    </li> 
</ul> 

Full code Example + HTML Demo

+0

嘿男人!它非常棒!非常感謝你... – redbaron76

+0

@ redbaron76:不客氣。如果它幫助你,請不要忘記接受答案:http://meta.stackexchange.com/q/5234/147909。 – hakre

+0

briliant,excelent ...謝謝 – Florin

相關問題