gpt4 book ai didi

php - 在第二个 while 循环内进行 while 循环以获取子类别

转载 作者:行者123 更新时间:2023-11-29 10:27:29 24 4
gpt4 key购买 nike

我需要在第二个 while 循环内编写 while 循环以获取子子类别。我只达到了二级。我怎样才能达到第三级?

<?php

include('db.php');
$sql = mysqli_query($db,"select cat_id,product from category where parent_id=0");
// parent_id categories node
$categories = array("Categories" => array());

while ($row = mysqli_fetch_array($sql,MYSQLI_ASSOC)) {
$cat_id = $row['cat_id'];
$ssql = mysqli_query($db,"select cat_id,product from category where parent_id='$cat_id'");



// single category node
$category = array(); // temp array
$category["cat_id"] = $row["cat_id"];
$category["product"] = $row["product"];
//$category["media"] = $row["media"];
$category["sub_categories"] = array(); // subcategories again an array

while ($srow = mysqli_fetch_array($ssql,MYSQLI_ASSOC)) {
$subcat = array(); // temp array
$subcat["cat_id"] = $srow['cat_id'];
$subcat["product"] = $srow['product'];
// pushing sub category into subcategories node
array_push($category["sub_categories"], $subcat);
}

// pushing sinlge category into parent_id
array_push($categories["Categories"], $category);
}
echo ((isset($_GET['callback'])) ? $_GET['callback'] : "") . '(' . json_encode($categories) . ')';
?>

这是实际的 TreeView

enter image description here

最佳答案

您可以创建递归函数来获取所有子类别:

function getSubCategories($cat_id) {

$sql = mysqli_query($db,"select cat_id,product from category where parent_id='$cat_id'");

$sub_categories = array();
while ($row = mysqli_fetch_array($sql, MYSQLI_ASSOC)) {

$cat_id = $row['cat_id'];

// single category node
$category = array(); // temp array
$category["cat_id"] = $row["cat_id"];
$category["product"] = $row["product"];
//$category["media"] = $row["media"];
$category["sub_categories"] = getSubCategories($cat_id); // subcategories again an array

array_push($sub_categories, $category);

}
return $sub_categories;

}


// parent_id categories node
$categories = array("Categories" => getSubCategories(0));

关于php - 在第二个 while 循环内进行 while 循环以获取子类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48033195/

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