导致嵌套列表的嵌套SQL


Nested SQL resulting to Nested List

关于如何在不需要重新创建大量select语句的情况下生成嵌套列表,有什么想法吗?

我目前正在使用这个代码

<ol>
<?php
$getparents=mysql_query("select id,subject from list");
    while($parent=mysql_fetch_assoc($getparents)){
?>
       <li><?php echo $parent["id"];?></li>
<?php
       $childsparent=$parent["id"];
       $getchild=mysql_query("select id,subject from list where parent_id='".$childsparent."'");
       if (!mysql_num_rows($getchild){
       echo '</ol>';
       }
       else
       {
       echo '<ol>';
       while ($child=mysql_fetch_assoc($getchild)){
       echo '<li>'.$child["subject"].'</li>';
       }
       $childsparent=$child["id"];
       }
?>
</ol>

有没有办法阻止这段时间获取所有结果,并在前进之前先检查一个结果是否有子嵌套?

结果应该类似

1.

2.

2.1

2.1.1

2.2

3

我发现了我前段时间写的这个函数。我认为这是你想要的那种东西。您只需要更改逻辑以打印出来,而不是存储到数组中:

function nestify( $arrs, $depth_key = 'depth' )
{
    $nested = array();
    $depths = array();
    foreach( $arrs as $key => $arr ) {
        if( $arr[$depth_key] == 0 ) {
            $nested[$key] = $arr;
            $depths[$arr[$depth_key] + 1] = $key;
        }
        else {
            $parent =& $nested;
            for( $i = 1; $i <= ( $arr[$depth_key] ); $i++ ) {
                $parent =& $parent[$depths[$i]];
            }
            $parent[$key] = $arr;
            $depths[$arr[$depth_key] + 1] = $key;
        }
    }
    return $nested;
}
$arr = array(
    array( 'name' => 'Joe Splogs', 'depth' => 0 ),
    array( 'name' => 'ProSplogger', 'depth' => 0 ),
    array( 'name' => 'Pinky Lyres', 'depth' => 1 ),
    array( 'name' => 'Pseudologia fantastica', 'depth' => 2 ),
    array( 'name' => 'TextLinkBarry', 'depth' => 1 ),
    array( 'name' => 'Foo bar Jones', 'depth' => 0 )
);
$new = nestify( $arr, 'depth' );
#-> Returns
array (
    '0' => array
        (
            'name' => 'Joe Splogs',
            'depth' => 0
        ),
    '1' => array
        (
            'name' => 'ProSplogger',
            'depth' => 0
            '2' => array
                (
                    'name' => 'Pinky Lyres',
                    'depth' => 1
                    '3' => array
                        (
                            'name' => 'Pseudologia fantastica',
                            'depth' => 2
                        ),
                ),
            '4' => array
                (
                    'name' => 'TextLinkBarry',
                    'depth' => 1
                ),
        ),
    '5' => array
        (
            'name' => 'Foo bar Jones',
            'depth' => 0
        ),
);