Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over a complex Associative Array in PHP

Tags:

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?

like image 839
Thomas Owens Avatar asked Aug 25 '08 13:08

Thomas Owens


2 Answers

Nest two foreach loops:

foreach ($array as $i => $values) {
    print "$i {\n";
    foreach ($values as $key => $value) {
        print "    $key => $value\n";
    }
    print "}\n";
}
like image 95
Konrad Rudolph Avatar answered Oct 08 '22 07:10

Konrad Rudolph


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
like image 40
Gordon Avatar answered Oct 08 '22 06:10

Gordon