gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 13:48:07 25 4
gpt4 key购买 nike

我有一个由 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>

有什么想法吗?谢谢

最佳答案

首先将对象映射到一个新的散列(数组),其中索引是 id:

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

然后将这个flat hash转置成一个树状结构,看这个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 .

关于php - 如何从对象的数组记录集中获取嵌套的 HTML 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8020947/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com