dimanche 26 juillet 2015

Multidimensional Array Foreach Loop

Here's what I have:

$nav = array (
    "home" ,
    "page 1" => array (
        "page 1.1" => array (
            "page 1.1.1"
            "page 1.1.2"
        ) ,
        "page 1.2"
    )
    "page 2" => array (
        "page 2.1"
    )
);

And here's what I want:

<nav>
    <ul>
        <li>page 1
            <ul>
                <li>page 1.1
                    <ul>
                        <li>page 1.1.1</li>
                        <li>page 1.1.2</li>
                    </ul>
                </li>
                <li>page 1.2</li>
            </ul>
        </li>
        <li>page 2
            <ul>
                <li>page 2.1</li>
            </ul>
        </li>
    </ul>
</nav>

What I have so far:

foreach ($nav as $key => $val) {
    if (!is_numeric($key)) {
        $nav_entry = $key;
    } else {
        $nav_entry = $val;
    }
    echo "<li>" . $nav_entry . "</li>";
}

My problem here is that, I need to have that foreach loop if and whenever there's a child array. On top of that, I need to somehow fit in an if statement to add in the <ul></ul> tag...

I started seeing stars... too confusing.

Aucun commentaire:

Enregistrer un commentaire