Created
November 11, 2012 23:13
-
-
Save mdsahib/4056664 to your computer and use it in GitHub Desktop.
Generating category tree as HTML unordered list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//error_reporting (0); | |
$arr = array | |
( | |
0=> array | |
( | |
'id' => 1, | |
'parent' => 0, | |
'status' => 2, | |
'slug' => 'clothes', | |
'title' => 'Clothes' | |
), | |
1 =>array | |
( | |
'id' => 2, | |
'parent' => 1, | |
'status' => 2, | |
'slug' => 'jeans', | |
'title' => 'Jeans' | |
), | |
2=> array | |
( | |
'id' => 3, | |
'parent' => 1, | |
'status' => 2, | |
'slug' => 'dresses', | |
'title' => 'Dresses' | |
), | |
3=> array | |
( | |
'id' => 4, | |
'parent' => 0, | |
'status' => 2, | |
'slug' => 'accessories', | |
'title' => 'Accessories' | |
), | |
4 => array | |
( | |
'id' => 5, | |
'parent' => 4, | |
'status' => 2, | |
'slug' => 'bags', | |
'title' => 'Bags' | |
), | |
5 => array | |
( | |
'id' => 6, | |
'parent' => 4, | |
'status' => 2, | |
'slug' => 'watches', | |
'title' => 'Watches' | |
), | |
6 => array | |
( | |
'id' => 7, | |
'parent' => 6, | |
'status' => 2, | |
'slug' => 'rolex', | |
'title' => 'Rolex' | |
) | |
) ; | |
$tree = array (); | |
foreach ($arr as $val) { | |
$tree [ $val['parent'] ] [] = $val; | |
} | |
//if you want to capture the output in a string. | |
ob_start(); | |
traverser ($tree , $tree [0]); | |
$output = ob_get_clean(); | |
function traverser ($array ,$arr) { | |
if (! $arr) | |
return; | |
echo "<ul>" . "</br>"; | |
foreach ($arr as $var ) { | |
echo "<li>" . "</br>"; | |
echo '<a href="/'.$var['slug'].'">'.$var['title'].'</a>'; | |
if (isset ($array [$var['id'] ])) | |
traverser ($array , $array [$var['id'] ] ) ; | |
echo "</li>"; | |
} | |
echo "</ul>"; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Trying to do this for a select query for a table with parent-child relationships. Any chance you can guide me how to? My table looks like this: id|name|parent_id| . Thank you.