gpt4 book ai didi

php - 将数组转换为 Ul-Li

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

我有一个这样的数组

Array
(
[0] => Array
(
[name] => Region
[id] => 3
[parent_id] => 2
[children] => Array
(
[0] => Array
(
[name] => Asia
[id] => 4
[parent_id] => 3
[children] => Array
(
[0] => Array
(
[name] => Central Asia
[id] => 6621
[parent_id] => 4
[children] => Array
(
[0] => Array
(
[name] => Afghanistan
[id] => 5
[parent_id] => 6621
[children] => Array
(
[0] => Array
(
[name] => Balkh
[id] => 6
[parent_id] => 5
[children] => Array
(
[0] => Array
(
[name] => Mazar-e-Sharif
[id] => 7
[parent_id] => 6
)

)

)

[1] => Array
(
[name] => Kabol
[id] => 10
[parent_id] => 5
)

[2] => Array
(
[name] => Qandahar
[id] => 12
[parent_id] => 5
)

)

)

)

)

[1] => Array
(
[name] => Middle East
[id] => 6625
[parent_id] => 4
[children] => Array
(
[0] => Array
(
[name] => Armenia
[id] => 14
[parent_id] => 6625
)

)

)

)

)

)

)

)

现在我想把这个数组转换成ul-li in tree formate

但它给了我奇怪的输出

例如 Region 我想要这样

<li id=3 parent_id=2 > Region </li>

这里我想使用 idparent_id 作为属性php函数是

    function olLiTree($tree)
{
echo '<ul>';
foreach($tree as $key => $item) {
if (is_array($item)) {
echo '<li>', $key;
olLiTree($item);
echo '</li>';
} else {
echo '<li>', $item, '</li>';
}
}
echo '</ul>';
}

region 的输出就像上面的函数一样

<ul>
<li>0
<ul>
<li>Region</li>
<li>3</li>
<li>2</li>
<li>children
<ul>

最佳答案

也许这就是您要寻找的递归。

function olLiTree( $tree ) {
echo '<ul>';
foreach ( $tree as $item ) {
echo "<li id=\"$item[id]\" parent_id=\"$item[parent_id]\" > $item[name] </li>";
if ( isset( $item['children'] ) ) {
olLiTree( $item['children'] );
}
}
echo '</ul>';
}

关于php - 将数组转换为 Ul-Li,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16837415/

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