如何从对象数组记录集中获取嵌套的HTML列表?

5

我有一个由SQL查询返回的对象数组,其中top_id是我的父ID字段:

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>

有什么想法吗?感谢。

“top_id” 是否表示一个子类属于哪个类别? - TaylorOtwell
1个回答

10
首先将对象映射到一个新的哈希(数组)中,其中索引是id
// map the array onto hash
$hash = array();
foreach($array as $object)
{
    $hash[$object->id] = array('object' => $object);
}

然后将这个扁平的哈希表转换为树状结构,请参考此答案中的另一个代码示例,这里只是相同的:

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

完整代码示例+HTML演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接