<ul class="navdrop">
<li>category
<ul>
<li>subcategory
<ul>
<li>subcategory</li>
</ul>
</li>
</ul>
</li>
</ul>
我们如何创建一个循环来使用php数据显示结构中的catgeory和sub类别
如果尝试while循环打印主要的catgeory
<li><a class="shopdrop"><?php echo stripslashes($catParent_result['Category_Name']); ?></a></li>
答案 0 :(得分:0)
使用嵌套数组,您只需编写一个生成html列表的递归函数:
<?php
// the example input data
$example = array(
"menu1" => "a",
"menu2" => "b",
"menu3" => array(
"submenu3.1" => "c",
"submenu3.2" => "d"
),
"menu4" => array(
"submenu4.1" => array ( "subsubmenu4.1.1" => "e"),
),
);
//
// print an ul menu out of a given (nested) array
//
function ulmenu($arr, $level=0)
{
if (empty($arr) || !is_array($arr) || sizeof($arr)<1) return;
// using a prefix is optional, for the purpose of learning,
// it makes the output more readable
$spaceprefix = str_repeat(" ", $level*4);
echo "\n${spaceprefix}<ul>\n";
foreach ($arr as $key => $value)
{
echo "${spaceprefix} <li>${key}";
if (is_array($value))
{
// recursive call of limenu
ulmenu($value, $level+1);
}
else
{
echo " : ${value}";
}
echo "</li>\n";
}
echo "${spaceprefix}</ul>";
}
ulmenu($example);
?>
这将生成
<ul>
<li>menu1 : a</li>
<li>menu2 : b</li>
<li>menu3
<ul>
<li>submenu3.1 : c</li>
<li>submenu3.2 : d</li>
</ul></li>
<li>menu4
<ul>
<li>submenu4.1
<ul>
<li>subsubmenu4.1.1 : e</li>
</ul></li>
</ul></li>
</ul>