Skip to content

Instantly share code, notes, and snippets.

@mdsahib
Created November 11, 2012 23:13
Show Gist options
  • Save mdsahib/4056664 to your computer and use it in GitHub Desktop.
Save mdsahib/4056664 to your computer and use it in GitHub Desktop.
Generating category tree as HTML unordered list
<?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>";
}
?>
@Cywaithaka
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment