yphastos
11/11/2012 - 11:13 PM

Generating category tree as HTML unordered list

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>";


}

?>