关于如何生成嵌套列表而不需要重新创建大量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
答案 0 :(得分:1)
我发现了一段时间以前写的这个功能。我认为这是你想要的东西。您只需要更改逻辑以打印出来而不是存储到数组:
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
),
);