我需要在while循环中写入while循环以获取子子类别。我只获得第二级。我怎样才能获得第3级?
<?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) . ')';
?>
这是实际的树视图
答案 0 :(得分:1)
您可以创建递归函数来获取所有子类别:
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));