0

我正在尝试制作一个类别树系统来显示无尽的类别。数据库设置如下:

ID PARENT_ID CATEGORY_NAME

PHP代码:

$cat_array = array();
$subcat_array = array(); 
if (mysqli_connect_errno())
          {
          echo "Failed to connect to MySQL: " . mysqli_connect_error();
          }         

$sql = mysqli_query($con, "SELECT * FROM `documents_category` WHERE ISNULL(parent_id)    ");
while($row = mysqli_fetch_array($sql))
{      $cat_array[] = $row;  
//echo $row['category_name'];
}  

// print_r($cat_array);


 $sql2 = mysqli_query($con, "SELECT * FROM `documents_category`
 WHERE parent_id IS NOT NULL ");
 while($row2 = mysqli_fetch_array($sql2))
 {      $subcat_array[] = $row2;  
 }  

 foreach ($cat_array as $value)

 {
    echo "{$value['category_name']}<br/>";  

    foreach ($subcat_array as $value2)

    {
            if($value2['parent_id'] == $value['id'])

            {
            echo "{$value2['category_name']}<br/>";
            }


    }

}

子类别将仅使用父母 ID。我可以把这个工作交给一个父母和一个孩子,但之后什么都没有出现。我已经尝试了几种不同的方法,但没有运气。有什么建议吗?

4

1 回答 1

0

您需要使用递归。通常我使用 PDO,但我试图做一个工作示例:

<?php
$cat_array = array();
$subcat_array = array(); 
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}         

function GetCategories($parent_id, $counter = 0)
{

    $sql = mysqli_query($con, "SELECT * FROM `documents_category` WHERE parent_id = " . (int)$parent_id);
    while($row = mysqli_fetch_array($sql))
    {
        echo str_repeat("&nbsp;", $counter) . $row["id"] . " - " . $row["parent_id"] . " - " . $row["category_name"];
        $sub_category = mysqli_query($con, "SELECT * FROM `documents_category` WHERE parent_id = " . (int)$row["id"]);
        $counter++;
        if(count($sub_category) > 0)
            GetCategories($row["id"], $counter);
    }
}

$parent_categories = GetCategories(0);
?>

如您所见,我通过调用该函数来选择“根”。它将呼应类别。然后它检查当前 id 上是否有子类别,如果找到则再次调用该函数,但现在使用当前行的 parent_id。如果没有找到,它会走得更远......你可以使用计数器来添加空格或其他东西......

于 2013-03-04T13:59:11.740 回答