I have an array ($nested) like this (this is the print_r() output)
Array
(
[1] => Array
(
[id] => 1
[module] => 1
[parent] => 0
[name] => Audio
)
[20] => Array
(
[id] => 20
[module] => 1
[parent] => 5
[name] => Mixer analogici
)
[16] => Array
(
[id] => 16
[module] => 1
[parent] => 4
[name] => Videoproiettori
)
[11] => Array
(
[id] => 11
[module] => 1
[parent] => 2
[name] => Strutture
)
...
[19] => Array
(
[id] => 19
[module] => 1
[parent] => 5
[name] => Mixer digitali
)
)
And a recursive function to create a nested menu:
function nmenu($module, $parent, $array) {
$has_children = false;
foreach($array as $key => $value) {
if ($value['module'] == $module) {
if ($value['parent'] == $parent) {
if ($has_children === false && $parent) {
$has_children = true;
echo "<ul>\n";
}
echo '<li>';
echo '' . $value['name'] . " \n";
nmenu($module, $key, $array);
echo "</li>\n";
}
}
}
if ($has_children === true && $parent) echo "</ul>\n";
}
That I call like this:
<ul>
<?php nmenu($row_rsNavModules['mod_id'], 0, $nested) ?>
</ul>
All is fine, the recursive function works as expected and it creates a series of infinite nested ULs… well, it’s the “infinite” that it’s too much: I’d like to limit the indentation level (aka the number of indented ULS) to 2, like this:
Cat 1
Subcat 1-1
Subcat 1-2
...
Cat 2
Subcat 2-1
Subcat 2-2
...
And NOT ending up like this:
Cat 1
Subcat 1-1
Sub-Subcat 1-1-1
Sub-Sub-Subcat 1-1-1-1
...
Please, how can I edit the previous function to achieve this?
Thanks in advance!
You only need to have a counter and quit from the function once the counter reaches your limit. Something like:
And call it like this: