Iterating over a complex Associative Array in PHP

Is there an easy way to iterate over an associative array of this structure in PHP:

The array $searches has a numbered index, with between 4 and 5 associative parts. So I not only need to iterate over $searches[0] through $searches[n], but also $searches[0]["part0"] through $searches[n]["partn"]. The hard part is that different indexes have different numbers of parts (some might be missing one or two).

Thoughts on doing this in a way that's nice, neat, and understandable?


Nest two foreach loops:

foreach ($array as $i => $values) {
    print "$i {\n";
    foreach ($values as $key => $value) {
        print "    $key => $value\n";
    }
    print "}\n";
}

I know it's question necromancy, but iterating over Multidimensional arrays is easy with Spl Iterators

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));

foreach($iterator as $key=>$value) {
    echo $key.' -- '.$value.'<br />';
}

See

  • http://php.net/manual/en/spl.iterators.php

Looks like a good place for a recursive function, esp. if you'll have more than two levels of depth.

function doSomething(&$complex_array)
{
    foreach ($complex_array as $n => $v)
    {
        if (is_array($v))
            doSomething($v);
        else
            do whatever you want to do with a single node
    }
}

You should be able to use a nested foreach statment

from the php manual

/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
}