I have an array in PHP, which looks like this:
array (
[0] => array (
[id] => 1
[title] => \"Title 1\"
[parent_id] =>
You should use recursion:
First the array in 'php' syntax:
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 = "";
foreach ( $a as $i ) {
if ($i['parent_id'] == $level ) {
$r = $r . "- " . $i['title'] . r( $a, $i['id'] ) . "
";
}
}
$r = $r . "
";
return $r;
}
print r( $a, $level );
?>
The results:
- 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 . "- " . $i['title'] . r( $a, $i['id'] ) . "
";
}
}
return ($r==''?'':"". $r . "
");
}