gpt4 book ai didi

php - 如何在下拉列表中创建无限子类别

转载 作者:行者123 更新时间:2023-11-30 01:19:16 24 4
gpt4 key购买 nike

您能指导我如何使用 php 和 mysql 在下拉列表中创建无限类别和子类别吗?

我是他们面前的子类别。例如第一子类---和第二级-----等等:我想实现这样的目标:-

<select name="category">
<option value="1">Root</option>
<option value="3">- Sub </option>
<option value="4">- - Sub</option>
<option value="5">Root</option>
<option value="6">- Sub </option>
<option value="7">- - Sub</option>
</select>

这是我到目前为止得到的代码

function get_category($parentID = 0){
global $mysqli;
$html = '';
// Prepare the query
$stmt = $mysqli->prepare("SELECT CategoryID, Title
FROM category
WHERE ParentID =?");
// Bind param
$stmt->bind_param('i', $parentID);

// Execute the query
$stmt->execute();

// Store the result
$stmt->store_result();

// Bind the result
$stmt->bind_result($categoryID, $title);
while($stmt->fetch()){
$html .= "<option value=\"$categoryID\">$title</option>";

$child = $mysqli->prepare("SELECT CategoryID
FROM category
WHERE ParentID =?");

// Execute the query
$child->bind_param('i', $categoryID);
$child->execute();

// Store the result
$child->store_result();

// Bind the result
$has_child = NULL;
$has_child = $child->num_rows;
if($has_child){
$html .= get_category($categoryID);
}
}

return $html;
}
echo '<select name="category">';
print(get_category());
echo '</select>';

感谢任何帮助

最佳答案

引用此link 。它是mysql格式的

也检查一下

<?php
// Get listing of base categories
$sql="SELECT cat_id, cat_name FROM cat_table where cat_parent='0' ORDER BY cat_name asc";
$basecat = mysql_query($sql) or die($sql);
print"<select name=\"category\">";
while($cat_list=mysql_fetch_array($basecat)){
if ($cat_list[0]==$cur_cat){$test= ' selected';}else{$test='';}
print '<option value="'.$cat_list[0].'"'.$test.'>'.$cat_list[1].'</option>';
sub_cat($cat_list[0]);// this calls the function for sub cats
}
print'</select>';
// ***********************************************************************
// Sub-Category Function
function sub_cat($cat_num){
$subcat = mysql_query("SELECT cat_id, cat_name FROM cat_table where cat_parent='$cat_num' ORDER BY cat_name asc");
while($sub_cat_list = mysql_fetch_array($subcat)){
if ($sub_cat_list[0]==$cur_cat){$test=' selected';}else{$test='';}
print '<option value="'.$sub_cat_list[0].'"'.$test.'>&nbsp;&nbsp;&nbsp;'.$sub_cat_list[1].'</option>';
}
}
// ***********

结果类似于这种格式

<select name="category">
<option value="4">Advertising</option>
<option value="8">&nbsp;&nbsp;&nbsp;Newspaper</option>
<option value="10">&nbsp;&nbsp;&nbsp;Radio</option>
<option value="9">&nbsp;&nbsp;&nbsp;Television</option>
<option value="2">Autos</option>
<option value="5">&nbsp;&nbsp;&nbsp;Chevy</option>
<option value="7">&nbsp;&nbsp;&nbsp;Dodge</option>
<option value="6">&nbsp;&nbsp;&nbsp;Ford</option>
<option value="3">Marketing</option>
</select>

已更新Link

关于php - 如何在下拉列表中创建无限子类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18731807/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com