如何从对象的数组记录集获取嵌套的HTML列表? [英] How to obtain a nested HTML list from object's array recordset?

查看:59
本文介绍了如何从对象的数组记录集获取嵌套的HTML列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 [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获取这样的嵌套列表:

Now I need to obtain a nested list like this using 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>

有什么主意吗? 谢谢

推荐答案

首先将对象映射到索引为id的新哈希(数组)中:

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

最后,您可以将这种树状结构输出为HTML.这可以通过堆栈或递归来完成.这是具有递归的一种变体:

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 '<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演示.

这篇关于如何从对象的数组记录集获取嵌套的HTML列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆