How to obtain a nested HTML list from object's array recordset?

后端 未结 1 844
盖世英雄少女心
盖世英雄少女心 2020-11-30 12:04

I have this array of objects returned by a SQL query where top_id is my parent ID field:

Array (
[0] => stdClass Object ( [id] => 1 [top_id] => 0 [n         


        
1条回答
  •  难免孤独
    2020-11-30 12:41

    First of all map the objects onto a new hash (array) in which the index is the id:

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

    Then transpose this flat hash into a tree-like structure, see this answer for another code example, it's merely the same here:

    // 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);
    

    Finally you can output this tree-like structure as HTML. This can be done with either a stack or recursive. This is one variant with recursion:

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

    Output:

    • Cat 1
    • Cat 2
      • Subcat 1
      • Subcat 2
        • Subcat 4
    • Cat 3
      • Subcat 3

    Full code Example + HTML Demo.

    0 讨论(0)
提交回复
热议问题