Halnex Halnex - 2 months ago 14
PHP Question

Retrieve array values inside foreach() loop

I am trying to output Wordpress' navigation menu items along with their CSS Classes.

I was able to get the menu items, but the classes are more complicated. the css classes come in an array but it's already inside a

foreach()
loop.

$menu_items = wp_get_nav_menu_items($menu->term_id);

$menu_list = '<ul id="menu-' . $menu_name . '">';

foreach ( (array) $menu_items as $key => $menu_item ) {
$title = $menu_item->title;
$url = $menu_item->url;
$classes = $menu_item->classes;

$menu_list .= '<li>';
$menu_list .= '<i class=""></i>';
$menu_list .= '<a href="' . $url . '">' . $title . '</a>';
$menu_list .= '</li>';
}

$menu_list .= '</ul>';


As you can see, inside the
foreach()
loop I am getting the
$title
and
$url
which are both strings. But then when I try to get the css classes associated with the menu item through
$menu_item->classes
it returns an array and I am not sure how to do this.

Because each menu item has 3 css classses
fa fa-user fa-3x
I can return the values using this

$classes[0] . $classes[1] . $classes[2]


But suppose I don't want the third class and I leave it out empty, I get a missing offset error.

I also tried doing a foreach within the original foreach

$menu_list .= '<li>';
foreach($classes as $class) {
$menu_list .= '<i class="'. $class .'"></i>';
}
$menu_list .= '<a href="' . $url . '">' . $title . '</a>';
$menu_list .= '</li>';


But this returns 3 separate
<i>
tags for each menu item, which is not what I want. The output looks like this

<i class="fa"></i>
<i class="fa-user"></i>
<i class="fa-3x"></i>

Answer

Simply use a nested Loop in place like so:

<?php

    $menu_items = wp_get_nav_menu_items($menu->term_id);

    $menu_list  = '<ul id="menu-' . $menu_name . '">';

    foreach ( (array) $menu_items as $key => $menu_item ) {
        $title      = $menu_item->title;
        $url        = $menu_item->url;
        $classes    = $menu_item->classes;
        $comboClass = "";

        // USING NESTED LOOP CONSTRUCT
        foreach($classes as $class){
            $comboClass .= $class . " "; // SEPARATE CLASS-NAME WITH A SPACE
        }

        $menu_list .= '<li>';
        $menu_list .= '<i class="' .$comboClass . '"></i>';
        $menu_list .= '<a href="' . $url . '">' . $title . '</a>';
        $menu_list .= '</li>';
    }

    $menu_list .= '</ul>';