July 31, 201115 yr I have some rows in my DB and each has a ['subpage'] value of either 0 or 1 to indicate if it is a main page(0) or subpage(1) and they are ordered (column 'item order') so the parents are above their children e.g. 1 home (0) 2 about(0) 3 about-sub(1) 4 about-another-sub(1) 5 page(0) 6 page-sub1(1) 7 contact(0) What would be the best way to loop through these as a nested ul? I would have personally preferred to give each sub page a parent id but the person that created the CMS just did it like this so I am stuck with it!
July 31, 201115 yr I take it this is how you want the output to be formatted (with the subnav ul within the <li> of it's parent) <?php $results = array( array( 'name' => 'home', 'subpage' => 0 ), array( 'name' => 'about', 'subpage' => 0 ), array( 'name' => 'about-sub', 'subpage' => 1 ), array( 'name' => 'about-another-sub', 'subpage' => 1 ), array( 'name' => 'page', 'subpage' => 0 ), array( 'name' => 'page-sub1', 'subpage' => 1 ) ); $pageTree = sortPages($results); $menuHTML = recurseMenu($pageTree); var_dump($menuHTML); function sortPages($array) { $results = array(); foreach($array as $r) { if(!$r['subpage']) { $results[] = array( 'name' => $r['name'], 'subpages' => array() ); } else { $results[(count($results) - 1)]['subpages'][] = array( 'name' => $r['name'], 'subpages' => array() ); } } return $results; } function recurseMenu($array, $level = 0) { $output = '<ul class="level-' . $level . '">'; foreach($array as $item) { $output .= '<li>' . $item['name']; if(!empty($item['subpages'])) { $output .= recurseMenu($item['subpages'], $level + 1); } $output .= '</li>'; } $output .= '</ul>'; return $output; } Edited July 31, 201115 yr by Jay Gilford
Create an account or sign in to comment