Question

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?

Was it helpful?

Solution

Nest two foreach loops:

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

OTHER TIPS

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

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";
    }
}

Can you just loop over all of the "part[n]" items and use isset to see if they actually exist or not?

I'm really not sure what you mean here - surely a pair of foreach loops does what you need?

foreach($array as $id => $assoc)
{
    foreach($assoc as $part => $data)
    {
        // code
    }
}

Or do you need something recursive? I'd be able to help more with example data and a context in how you want the data returned.

Consider this multi dimentional array, I hope this function will help.

$n = array('customer' => array('address' => 'Kenmore street',
                'phone' => '121223'),
      'consumer' => 'wellington consumer',
      'employee' => array('name' => array('fname' => 'finau', 'lname' => 'kaufusi'),
                     'age' => 32,
                 'nationality' => 'Tonga')
      );



iterator($n);

function iterator($arr){

    foreach($arr as $key => $val){

    if(is_array($val))iterator($val);

    echo '<p>key: '.$key.' | value: '.$val.'</p>';

    //filter the $key and $val here and do what you want
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top