Andrew Sunset
Andrew Sunset

Reputation: 39

How to iterate a PHP Array in HTML

I've trying to iterate the following array of PHP inside and HTML template:

$sub_menu = array(
    array(
        'titulo' => 'Ropa',
        'url' => '/ropa.html
    '),
    array(
        'titulo' =>'Electronica',
        'url' => '/electronica.html'
    ),
    array(
        'titulo' => 'Higiene',
        'url' =>'/higiene.html'
    ),
    array(
        'titulo' => 'Alimentos',
        'url' => '/alimentos.html'
    ),
    array(
        'titulo' => 'Otros',
        'url' => '/otros.html'
    )
);

Hadn't been lucky so far. What I'm trying to do is to show this as a list inside of a nav tag.

Could you please lend me a hand?

So I tried this

<?php 
echo '<ul>'; 
foreach ($sub_menu as $parent) { 
    if (is_array($parent)) { 
        echo '<ul>'; 
        foreach ($parent as $children => $key) { 
            echo '<li><a href="#">' . $children . '</a>'; 
        } 
        echo '</ul>'; 
    } 
    echo '</li>'; 
} 
echo '</ul>'; 
?>

Upvotes: 0

Views: 58

Answers (3)

Forge Web Design
Forge Web Design

Reputation: 835

You have echo ul on wrong place try the following code

<?php   
echo "<ul>";
foreach ($sub_menu as $parent) { 
    if (is_array($parent)) { 
        echo '<li><ul>'; 
        foreach ($parent as $children => $key) { 
            echo '<li><a href="#">' . $children . '</a>'; 
        } 
        echo '</ul></li>'; 
    }else {
        echo '<li><a href="#">' . $parent . '</a>'; 
    } 

} 
 echo "</ul>";
?>

Upvotes: 0

RiggsFolly
RiggsFolly

Reputation: 94642

I think you made it all a bit more complex than the input array required

$sub_menu = array(
    array(
        'titulo' => 'Ropa',
        'url' => '/ropa.html'),
    array(
        'titulo' =>'Electronica',
        'url' => '/electronica.html'
    ),
    array(
        'titulo' => 'Higiene',
        'url' =>'/higiene.html'
    ),
    array(
        'titulo' => 'Alimentos',
        'url' => '/alimentos.html'
    ),
    array(
        'titulo' => 'Otros',
        'url' => '/otros.html'
    )
);

echo '<ul>'.PHP_EOL; 
foreach ($sub_menu as $parent) { 
    echo '<li><a href="' . $parent['url'] . '">' . $parent['titulo'] . '</a></li>'.PHP_EOL; 
} 
echo '</ul>'.PHP_EOL; 

RESULT

<ul>
<li><a href="/ropa.html">Ropa</a></li>
<li><a href="/electronica.html">Electronica</a></li>
<li><a href="/higiene.html">Higiene</a></li>
<li><a href="/alimentos.html">Alimentos</a></li>
<li><a href="/otros.html">Otros</a></li>
</ul>

Upvotes: 1

jibsteroos
jibsteroos

Reputation: 1391

Use a basic foreach() loop to render your 'navbar'... edit the HTML to suit your specific needs:

foreach ($sub_menu as $key => $value) {
        echo "<li><a href='" . $value['url'] . "'>" . $value['titulo'] . "</a></li>";
}

Upvotes: 0

Related Questions