eval.in

Paste #81041

PHP — PHP 5.5.1, pasted 1 year ago

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
$menu = array(
	0 => array(
		array('id' => 1, 'parent_id' => 0, 'title' => 'First level #1'),
		array('id' => 2, 'parent_id' => 0, 'title' => 'First level #2'),
		array('id' => 3, 'parent_id' => 0, 'title' => 'First level #3'),
	),
	1 => array(
		array('id' => 8, 'parent_id' => 2, 'title' => 'Second level #8'),
	),
	2 => array(
		array('id' => 4, 'parent_id' => 2, 'title' => 'Second level #4'),
		array('id' => 5, 'parent_id' => 2, 'title' => 'Second level #5'),
	),
	4 => array(
		array('id' => 6, 'parent_id' => 4, 'title' => 'Third level #6'),
		array('id' => 7, 'parent_id' => 4, 'title' => 'Third level #7'),
	),
);

function generateMenu(array $menu, $parentId = 0) {
	if (!isset($menu[$parentId])) {
		return;
	}
	$output = "<ul>\n";
	foreach ($menu[$parentId] as $record) {
		$output .= "<li>\n";
		$output .= '<a href="#">' . $record['title'] . "</a>\n";
		$output .= generateMenu($menu, $record['id']);
		$output .= "</li>\n";
	}
	$output .= "</ul>\n";
	return $output;
}

echo generateMenu($menu);

Program Output

<ul>
<li>
<a href="#">First level #1</a>
<ul>
<li>
<a href="#">Second level #8</a>
</li>
</ul>
</li>
<li>
<a href="#">First level #2</a>
<ul>
<li>
<a href="#">Second level #4</a>
<ul>
<li>
<a href="#">Third level #6</a>
</li>
<li>
<a href="#">Third level #7</a>
</li>
</ul>
</li>
<li>
<a href="#">Second level #5</a>
</li>
</ul>
</li>
<li>
<a href="#">First level #3</a>
</li>
</ul>

OK (0.012 sec real, 0.009 sec wall, 14 MB, 42 syscalls)

Fork