SELECT查询并在PHP中创建一个infinate循环

时间:2016-02-12 12:14:03

标签: php

我正在尝试在PHP中创建多个循环来选择父项和子项。我有这个代码:

<?php
$counter = 0;
$sql="SELECT * from shop_categories where parent = '' order by name ASC ";
$rs=mysql_query($sql,$conn);
while($result = mysql_fetch_array($rs)) {
    $flag = 1;
    $current_parent_sequence = $result["sequence"];

    echo '<strong>'.$result["name"].'</strong><br>';

    while($flag == 1) {
        $counter++;

        $sql2="SELECT * from shop_categories where parent = '".$current_parent_sequence."' order by name ASC ";
        $rs2=mysql_query($sql2,$conn);
        if(mysql_num_rows($rs2) > 0) {
            while($result2=mysql_fetch_array($rs2)) {
                $current_parent_sequence = $result2["sequence"];

                echo $counter.' - '.$result2["name"].'<br>';
            }
        } else {
            $flag = 0;
        }
    }
}
?>

然后我在表格中提供了这些数据 - http://postimg.org/image/o2p31xd1j/

所以它应该显示父项及其子项及其子项等,但它只显示:

Cat 1
1 - Sub Cat 1
1 - Sub Cat 2
Cat 2
Cat 3
4 - Sub Cat 1

1 个答案:

答案 0 :(得分:2)

请尝试以下代码。它可能对你有帮助。你需要创建函数,它将递归调用。

function getChild($conn, $id) {
    $rs=mysqli_query($conn, "SELECT * from test_tbl where parent = '$id' order by name ASC ");
    while($result = mysqli_fetch_assoc($rs)) {
        $current_parent_sequence = $result["sequence"];
        $parent = $result["parent"];
        echo "--" . $result["name"] . "<br>";
        if($parent != 0)
            getChild($conn, $current_parent_sequence);
    }
}

$rs=mysqli_query($conn, "SELECT * from test_tbl where parent = '' order by name ASC ");
while($result = mysqli_fetch_assoc($rs)) {
    $current_parent_sequence = $result["sequence"];
    $parent = $result["parent"];
    echo $result["name"] . "<br>";
    getChild($conn, $current_parent_sequence);
}

使用mysqli,因为mysql已被弃用。