You should use recursion:
First the array in 'php' syntax:
<?php
$a=array (
'0' => array (
'id' => 1,
'title' => "Title 1",
'parent_id' => 'NULL',
'depth' => 0
),
'1' => array (
'id' => 2,
'title' => "Title 2",
'parent_id' => 'NULL',
'depth' => 0
),
'2' => array (
'id' => 3,
'title' => "Title 3",
'parent_id' => 2,
'depth' => 1
),
'3' => array (
'id' => 4,
'title' => "Title 4",
'parent_id' => 2,
'depth' => 1
),
'4' => array (
'id' => 5,
'title' => "Title 5",
'parent_id' => 'NULL',
'depth' => 0
),
'5' => array (
'id' => 6,
'title' => "Title 6",
'parent_id' => 4,
'depth' => 0
)
);
Here the code:
$level = 'NULL';
function r( $a, $level) {
$r = "<ol>";
foreach ( $a as $i ) {
if ($i['parent_id'] == $level ) {
$r = $r . "<li>" . $i['title'] . r( $a, $i['id'] ) . "</li>";
}
}
$r = $r . "</ol>";
return $r;
}
print r( $a, $level );
?>
The results:
<ol><li>Title 1<ol></ol></li><li>Title 2<ol><li>Title 3<ol>
</ol></li><li>Title 4<ol><li>Title 6<ol></ol></li></ol></li></ol></li><li>Title 5
<ol></ol></li></ol>
- Title 1
- Title 2
- Title 3
- Title 4
- Title 6
- Title 5
EDITED AFTER CHECK AS SOLUTION
To avoid empty leafs:
function r( $a, $level) {
$r = '' ;
foreach ( $a as $i ) {
if ($i['parent_id'] == $level ) {
$r = $r . "<li>" . $i['title'] . r( $a, $i['id'] ) . "</li>";
}
}
return ($r==''?'':"<ol>". $r . "</ol>");
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…