我有阵列:
父母1是第一步!
Array
(
[0] => Array
(
[categoryID] => 1
[parent] => 1
[name] => 111
)
[1] => Array
(
[categoryID] => 2
[parent] => 1
[name] => 2222
)
[2] => Array
(
[categoryID] => 3
[parent] => 2
[name] => 3333
)
[3] => Array
(
[categoryID] => 4
[parent] => 3
[name] => 444
)
)
结果我需要具有ul和li元素的树结构:
<ul>
<li>111</li>
<li>222
<ul>
<li>333
<ul>
<li>444</li>
</ul>
</li>
</ul>
</li>
</ul>
谢谢!
答案 0 :(得分:0)
这个数组看起来很像是从数据库中获取的。如果是这种情况,请使用MVC框架。它会让你的生活变得更加轻松。
答案 1 :(得分:0)
<?php
$input_array = array(
array(
'categoryID' => 1,
'parent' => 1,
'name' => 111,
),
array(
'categoryID' => 2,
'parent' => 1,
'name' => 2222,
),
array(
'categoryID' => 3,
'parent' => 2,
'name' => 3333,
),
array(
'categoryID' => 4,
'parent' => 3,
'name' => 444,
)
);
function buildHtmlList($array)
{
$maxlevel = 0;
// just to be sure that the array keys are continuous
$array = array_values($array);
foreach ($array as $key => $value)
{
$previousparent = isset($array[$key - 1]['parent']) ? $array[$key - 1]['parent'] : null;
$nextparent = isset($array[$key + 1]['parent']) ? $array[$key + 1]['parent'] : null;
if ($value['parent'] != $previousparent)
{
echo "\n<ul>";
++$maxlevel;
}
echo "\n<li>" . $value['name'];
if ($nextparent == $value['parent'])
echo "</li>";
}
for ($i = 0; $i < $maxlevel; ++$i)
{
echo "\n</li>\n</ul>";
}
}
buildHtmlList($input_array);