Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Nested list php while loop problem

Featured Replies

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!

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 by Jay Gilford

  • Author

THat seems to have done the trick! Thanks!

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.