【发布时间】:2013-05-26 02:27:04
【问题描述】:
我有一个这样的数组
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
但它给了我奇怪的输出
例如Region我想要这样
<li id=3 parent_id=2 > Region </li>
这里我想使用id 和parent_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>';
}
上面函数的区域输出是这样的
<ul>
<li>0
<ul>
<li>Region</li>
<li>3</li>
<li>2</li>
<li>children
<ul>
【问题讨论】:
-
你能指定你目前得到什么输出吗?
-
你能编辑你的问题并添加你的输出吗..
-
您的 foreach 循环不正确。您必须将 $item['children'] 作为函数的属性以使其递归。
标签: php arrays function multidimensional-array