while循环里面循环得到子子类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了while循环里面循环得到子子类相关的知识,希望对你有一定的参考价值。

我需要在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) . ')';
?>

这是实际的树视图

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));

以上是关于while循环里面循环得到子子类的主要内容,如果未能解决你的问题,请参考以下文章

python中的while循环与for循环怎么样那个比较好用?

for循环结构

while循环嵌套需要注意的点,

SQL——While循环

SQL——While循环

MySQL 中的 While 循环使用连接和子查询选择数据