问问题
771 次
2 回答
0
对我有用的代码,我上面的问题最终如下。我只需要计算调用递归函数来填充 select 的次数,每次函数进入新级别的类别时,我都可以根据需要使用计数值重复一个 ' ' 字符串,为递归的每个级别。
这正确对齐了选择中每个类别中的节点,因此用户可以看到哪些子类别属于哪个父类别。
我为此使用了一个静态变量,但打算用更好的方法替换它。
我发布了创建选择下拉列表的部分代码,以防有人发现它有用。
function printTree($tree) {
function printChildren($childrenarray) {
static $level = 1;
if(!is_null($childrenarray) && count($childrenarray) > 0){
$level++;
foreach($childrenarray as $node) {
echo '<option>'.str_repeat(' ', $level).$node['name'].'</option>';
printChildren($node['children']);
}
--$level;
}
}
if(!is_null($tree) && count($tree) > 0){
foreach($tree as $node) {
echo '<option bg-danger>'.$node['name'].'</option>';
if (!is_null($node['children']) && count($node['children']) > 0 ) {
printChildren($node['children']);
}
}
}
}
于 2019-04-19T18:53:19.420 回答
0
据我了解,如果 categoryid 可以区分所有产品,那么我的回答对您有用。
无需再次离开同一张表。
$sql = 'select cat_ID from categories_tbl';
$result = mysqli_query($db, $sql);
echo '<select class="form-control">';
while ($row = mysqli_fetch_assoc($result)){
$sqlcat_name = "select cat_Name from categories_tbl where parent_ID="."'".$row['cat_ID']."'";
// echo this query to check that properly formed
$Secondresult = mysqli_query($db, $sqlcat_name);
$num_rows = mysql_num_rows($Secondresult);
$Secondrow = mysqli_fetch_assoc($Secondresult)
for($a=0;$a<$num_rows;$a++){
echo'<option>';
for($b=0;$b<$a;$b++){
echo" ";
}
echo "$Secondrow[$a]"."</option>";
}
}
echo '</select>';
于 2019-04-18T09:28:49.687 回答