具有子子类别的子类别的PHP类别

时间:2013-03-04 13:45:18

标签: php mysql loops categories

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

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。我可以让这个工作到一个父母和一个子,但是之后没有任何东西显示出来。我尝试了几种不同的方法,但没有运气。有什么建议吗?

1 个答案:

答案 0 :(得分: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);
?>

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