Quantcast
Channel: Iterate over all items and sub items in a PHP array - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Iterate over all items and sub items in a PHP array

$
0
0

I have a huge PHP array which holds the navigation structure of the site. It basically looks like this:

$navMap = array(
    array(
        'title' => 'Home',
    ), array(
        'title' => 'about us',
        'subNav' => array(
            array(
                'title' => 'Sub item 1',
                'subNav' => array(
                    array(
                        'title' => 'Sub sub item 1',
                    ),  array (
                        'title' => 'Sub sub item 2',
                    )
                ),
            ), array (
                'title' => 'Sub item 2',
            ), array (
                'title' => 'Sub item 3',
            )
        )
    )
);

I have a folder structure which would make the "Sub sub item 2" page link /pages/1/0/1.php since it is in the second of the primary nav items, the 1st of the secondary nav items and the 2nd of the tertiary nav items.

Instead of writing the links into the array which is prone to human error, I'm using PHP to add the links for me. This is what I'm doing at the moment:

for ($a = 0; $a < count($navMap); $a++) {
    $navMap[$a]['link'] = '/pages/'.$a.'.php';

    if (isset($navMap[$a]['subNav'])){

        for ($b = 0; $b < count($navMap[$a]['subNav']); $b++) {
            $navMap[$a]['subNav'][$b]['link'] = '/pages/'.$a.'/'.$b.'.php';

            if (isset($navMap[$a]['subNav'][$b]['subNav'])){

                for ($c = 0; $c < count($navMap[$a]['subNav'][$b]['subNav']); $c++) {
                    $navMap[$a]['subNav'][$b]['subNav'][$c]['link'] = '/pages/'.$a.'/'.$b.'/'.$c.'.php';
                }
            }

        }
    }
}

It's a really ugly solution though. Does anyone know a better way of adding the links to the array?

I'm after a solution that can detect an infinite number of levels on it's own with out having to add extra code for every extra level added. My current solution must be edited every time a new level is added to the $navMap.


Viewing all articles
Browse latest Browse all 3

Latest Images

Trending Articles





Latest Images