cnkt Posted January 20, 2009 Share Posted January 20, 2009 i have a db table structure of categories and sub categories like this: id name parent 1 top cat 1 0 2 sub Cat of top cat 1 1 3 sub Cat 1 of sub cat 1 of top cat 1 2 4 top cat 2 0 i have a code to get these structure of db to an array. the result array is like this (print_r used): Array ( [0] => Array ( [id] => 1 [ad] => top cat 1 [level] => 0 ) [1] => Array ( [0] => Array ( [id] => 2 [ad] => sub cat 1 of top cat 1 [level] => 1 ) [1] => Array ( [0] => Array ( [id] => 4 [ad] => sub cat 1 of sub cat 1 of top cat 1 [level] => 2 ) [1] => Array ( [id] => 6 [ad] => sub cat 2 of sub cat 1 of top cat 1 [level] => 3 ) [2] => Array ( [id] => 7 [ad] => sub cat 3 of sub cat 1 of top cat 1 [level] => 4 ) ) [2] => Array ( [id] => 3 [ad] => sub cat 2 of top cat 1 [level] => 2 ) ) [2] => Array ( [id] => 5 [ad] => top cat 2 [level] => 1 ) ) now, i need a function to render this array to html's <ul><li> list. can someone help me or have got a snippet for this? Link to comment https://forums.phpfreaks.com/topic/141585-category-sub-category-array-to-html-list-conversion/ Share on other sites More sharing options...
Mark Baker Posted January 20, 2009 Share Posted January 20, 2009 If you have the function to parse the data from the database into a nested array, then you also have all the logic that you need to parse it into a series of nested lists. Otherwise something like: $items = array( array('id' => '1', 'parent' => '0'), array('id' => '2', 'parent' => '0'), array('id' => '3', 'parent' => '0'), array('id' => '4', 'parent' => '1'), array('id' => '5', 'parent' => '1'), array('id' => '6', 'parent' => '1'), array('id' => '7', 'parent' => '2'), array('id' => '8', 'parent' => '4') ); function showLevel($items,$parent) { $ulSet = False; foreach ($items as $item) { if ($item['parent'] == $parent) { if (!$ulSet) { $ulSet = True; echo '<ul>'; } echo '<li>'.$item['id'].'</li>'; showLevel($items,$item['id']); } } if ($ulSet) { echo '</ul>'; } } showLevel($items,'0'); Link to comment https://forums.phpfreaks.com/topic/141585-category-sub-category-array-to-html-list-conversion/#findComment-741405 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.