Make a menu as tree by associative array PHP

Make a menu as tree by associative array PHP

    function menu($arr) {
        echo "<ul>";
        foreach ($arr as $val) {

            if (!empty($val['children'])) {
                echo "<li>" . $val['name'];
                menu($val['children']);
                echo "</li>";
            } else {
                echo "<li>|</li>";
                echo "<li>-&gt;" . $val['name'] . "</li>";
            }
        }
        echo "</ul>";
    }

    $arr = array(
	  array('id'=&gt;100, 'parentid'=&gt;0, 'name'=&gt;'a'),
	  array('id'=&gt;101, 'parentid'=&gt;100, 'name'=&gt;'a'),
	  array('id'=&gt;102, 'parentid'=&gt;101, 'name'=&gt;'a'),
	  array('id'=&gt;103, 'parentid'=&gt;101, 'name'=&gt;'a'),
	);

	$new = array();
	foreach ($arr as $a){
	    $new[$a['parentid']][] = $a;
	}
	
	$tree = createTree($new, array($arr[0]));
	echo('<pre>');
	//print_r($tree);
	echo('</pre>');
	menu($tree);

	function createTree(&amp;$list, $parent){
	    $tree = array();
	    foreach ($parent as $k=&gt;$l){
	        if(isset($list[$l['id']])){
	            $l['children'] = createTree($list, $list[$l['id']]);
	        }
	        $tree[] = $l;
	    } 
	    return $tree;
	}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s