以递归方式获取孩子的孩子

时间:2016-11-29 03:53:55

标签: php mysql recursion hierarchy

我有一个包含两列id和父ID

的表

data base image

想得到小孩的孩子的递归结果小孩等 在这个例子中我想要实现像

这样的结果

parent_id = 2

enter image description here

表示父亲第一次是2 下次结果将作为父母 像4,5,6,15是id,2是父ID 下次4,5,6,15将用作父ID 结果将是id = 7,8,13,14,16,他们的id = 4,5,6和15

这将一直持续到最后一个孩子。

1 个答案:

答案 0 :(得分:0)

也许它可以帮到你

   <?php
$serverName = "localhost"; //serverName\instanceName

// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array( "Database"=>"jdih");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
     echo "Connection established.<br />";
}else{
     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
}



function count_data($var)
{
    $serverName = "localhost";
    $connectionInfo = array( "Database"=>"jdih");
    $conn = sqlsrv_connect( $serverName, $connectionInfo);
    $sql = "SELECT count(*) total from test where parent_id = '".$var."'";
    $stmt = sqlsrv_query( $conn, $sql );
    $rowChild = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);
    return $rowChild['total'];
}



$sql = "SELECT id from test where parent_id = 0";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );
}

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) { 
    $totalchild = count_data($row['id']);
    if($totalchild > 0){
        $sqlchild = "select id from test where parent_id = '".$row['id']."'";
        $stmtchild = sqlsrv_query( $conn, $sqlchild);
            while( $rowChild = sqlsrv_fetch_array( $stmtchild, SQLSRV_FETCH_ASSOC) ){
                //
                    $totalchild2 = count_data($rowChild['id']);
                    if($totalchild2 > 0){
                        $sqlchild2 = "select id from test where parent_id = '".$rowChild['id']."'";
                        $stmtchild2 = sqlsrv_query( $conn, $sqlchild2);
                        while( $rowChild2 = sqlsrv_fetch_array( $stmtchild2, SQLSRV_FETCH_ASSOC) ){
                            echo $row['id']. ' Has ' . $rowChild['id'].' has '.$rowChild2['id']. '<br>';
                        }

                    }else{
                        echo $row['id']. ' Has ' . $rowChild['id'].'<br>';
                    }
            }
    }else{
        echo $row['id']. ' Has nothing';
    }

}



?>

这是一个例子,我使用的是sql。它不是动态的,但如果只有两个级别可能会有所帮助。如果有孩子,您可以添加conditional check

enter image description here

抱歉坏英语