我有一个如下所示的数据库。我需要从子类别创建一个类别的路径。
例如:网站显示,父母>小孩>小孩>子
SELECT * FROM category ORDER BY category_id;
+-------------+----------------------+--------+
| category_id | name | parent |
+-------------+----------------------+--------+
| 1 | ELECTRONICS | NULL |
| 2 | TELEVISIONS | 1 |
| 3 | TUBE | 2 |
| 4 | LCD | 2 |
| 5 | PLASMA | 2 |
| 6 | PORTABLE ELECTRONICS | 1 |
| 7 | MP3 PLAYERS | 6 |
| 8 | FLASH | 7 |
| 9 | CD PLAYERS | 6 |
| 10 | 2 WAY RADIOS | 6 |
+-------------+----------------------+--------+
当我选择" 7 | MP3播放器"我想要显示如下。
电子>便携式电子设备> MP3播放器
我在这里使用哪种技术?
答案 0 :(得分:0)
尝试以下代码。通过递归函数,它是可能的。
function fetchCategoryTree($parent = 0, $spacing = '', $user_tree_array = '') {
if (!is_array($user_tree_array))
$user_tree_array = array();
$sql = "SELECT `category_id`, `name`, `parent` FROM `category` WHERE 1 AND `parent` = $parent ORDER BY cid ASC";
$query = mysql_query($sql);
if (mysql_num_rows($query) > 0) {
while ($row = mysql_fetch_object($query)) {
$user_tree_array[] = array("id" => $row->category_id, "name" => $spacing . $row->name);
$user_tree_array = fetchCategoryTree($row->category_id, $spacing . '---', $user_tree_array);
}
}
return $user_tree_array;
}
$categoryList = fetchCategoryTree();
?>
<select>
<?php foreach($categoryList as $cl) { ?>
<option value="<?php echo $cl["id"] ?>"><?php echo $cl["name"]; ?></option>
<?php } ?>
</select>