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

Answer by Rob for Iterate over all items and sub items in a PHP array

$
0
0

You could use a foreach loop and string interpolation:

foreach ($navMap as $a => &$nm) {
    $nm['link'] = "/pages/$a.php";
    if (isset ($nm['subNav'])) {
        foreach ($nm['subNav'] as $b => &$sn) {
            $sn['link'] = "/pages/$a/$b.php";
            if (isset ($sn['subNav'])) {
                foreach ($sn['subNav'] as $c => &$sn2) {
                    $sn2['link'] = "/pages/$a/$b/$c.php";
                }
            }
        }
    }
}

The foreach iterates without having use the counters (but you can access them if needed as shown using the "$a =>" construct).

The &$nm accesses the actual variable instead of a copy so you can assign to it.

String interpolation allows you to construct more readable strings without having to use concatenation.


Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>