我创建的数据库看起来像这样
cat_id cat_parent_id cat_name cat_decs
11 0 Men for men
12 0 Women for women
13 11 Men clothing 123
14 12 Women cloth 434
我想这样打印
Men
Men clothing
Women
Women cloth
无论是在我的菜单栏还是在组合框中,我都试图找到解决方案,但一切都消失了,我已经使用了这个功能,但它是这样打印的
Men
Women
Men clothing
Women cloth
function buildCategoryOptions($catId = 0)
{
//die();
$sql = "SELECT cat_id, cat_parent_id, cat_name
FROM tbl_category
ORDER BY cat_id";
$result = mysql_query($sql) or die('Cannot get Product. ' . mysql_error());
$categories = array();
while($row = mysql_fetch_array($result)) {
list($id, $parentId, $name) = $row;
//echo $id, $parentId, $name;
if ($parentId == 0) {
// we create a new array for each top level categories
$categories[$id] = array('name' => $name, 'children' => array());
}
else {
// the child categories are put int the parent category's array
$categories[$parentId]['children'][] = array('id'=> $id, 'name'=> $name);
}
}
echo ($categories[28]['children'][0]['name']);
// build combo box options
$list = '';
foreach ($categories as $key => $value) {
$name= @$value['name'];
//print_r($value['name']);
$children = $value['children'];
$list .= "<optgroup label=\"$name\">";
foreach ($children as $child) {
$list .= "<option value=\"{$child['id']}\"";
if ($child['id'] == $catId) {
$list.= " selected";
}
$list .= ">{$child['name']}</option>\r\n";
}
$list .= "</optgroup>";
//die();
}
//die();
return $list;
}