Skip to content

Instantly share code, notes, and snippets.

@agborkowski
Forked from mdsahib/tree.php
Created February 11, 2014 11:56
Show Gist options
  • Save agborkowski/8933537 to your computer and use it in GitHub Desktop.
Save agborkowski/8933537 to your computer and use it in GitHub Desktop.
<?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