Cómo construir una navegación multinivel con PHP
Frecuentes
Visto 512 veces
0
Im working on a prototype, and would like to build a multi level navigation - however not by looping through an array. I have a $depth and a $children, which should determine the depth of the navigation and the number of children on each level. So $depth = 4, $children = 8 would yield 4096 menu items.
This is a snippet af the output I would like:
<ul>
<li class="level-1">
<a href="#">Subject 1</a>
<ul>
<li class="level-2">
<a href="#">Subject 1.1</a>
<ul>
<li class="level-3">
<a href="#">Subject 1.1.1</a>
</li>
...
</ul>
</li>
...
</ul>
</li>
...
</ul>
So far I have tried this, but I cant get my head around it :(
function draw_list ($depth, $children) {
echo '<ul>';
for ($i = 0; $i < $children; $i++) {
echo '<li>' . ($i++);
$depth--;
if ($depth > 0) {
echo draw_list($depth, $children);
}
echo '</li>';
}
echo '</ul>';
}
2 Respuestas
0
Several things required as I see it...
- Programas de
$depth--;
tiene que estar fuera de lafor
loops - You were incrementing
$i
dos veces, una vez en elfor
statement, and then again on theecho '<li>' . ($i++);
The $depth check was stopping one early, so make(Editar, thinking about it, this is an incorrect statement)>=
en lugar de solo>
That should give you...
function draw_list ($depth, $children) {
echo '<ul>';
$depth--;
for ($i = 0; $i < $children; $i++) {
echo '<li>' . $i;
if ($depth > 0) {
echo draw_list($depth, $children);
}
echo '</li>';
}
echo '</ul>';
}
Noticias
For the display of the level numbering, try passing a string value through as a parameter...
function draw_list ($depth, $children, $display=''){
echo '<ul>';
$depth--;
for ($i = 0; $i < $children; $i++) {
echo '<li>' . $display . ($i + 1);
if ($depth > 0) {
echo draw_list($depth, $children, $display . ($i + 1) . '.');
}
echo '</li>';
}
echo '</ul>';
}
Respondido 26 ago 12, 22:08
0
Terminé haciendo esto:
function build_nav ($depth, $children, $levels = array()) {
echo '<ul>';
$depth--;
for ($i = 0; $i < $children; $i++) {
$levels[$depth] = $i+1;
echo '<li>';
echo 'Subject: ' . implode('.', $levels);
if ($depth > 0) {
build_nav($depth, $children, $levels);
}
echo '</li>';
}
echo '</ul>';
}
Respondido 26 ago 12, 22:08
If it works, it works. But it looks to me like you're setting the array at the wrong level, as depth will decrease not increase. Also you've made me realise that my example will have the values one too low - Freefaller
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas php html arrays navigation html-lists or haz tu propia pregunta.
Thank you! Now I need to figure out how to print the level numbers (1.3.3.7 etc). I properly have to build an array and implode. Any ideas? - tolborg
@tolborg, Add string parameter, in the for loop create new sting using the parameter and the child index which you display and then pass as parameter in the recursion - Freefaller