21

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?

7 Answers 7

43

Nest two foreach loops:

foreach ($array as $i => $values) {
    print "$i {\n";
    foreach ($values as $key => $value) {
        print "    $key => $value\n";
    }
    print "}\n";
}
Sign up to request clarification or add additional context in comments.

2 Comments

is $i and $values a copy temp variable from the associative array or do they refer to the actual array reference?
@MMAmail.com: This code doesn’t use references, it uses copies. If you really want to use references (but you usually don’t!) you need to prefix the variable names with ampersand, i.e. &$i and &$values in their declaration and you should unset the variables after the loop.
42

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

3 Comments

Whats happens if one of the array elements is an iteratable object?
do you know how to exclude it from being iterated?, so only arrays are iterated?
@Petah wrap the iteratoror into a FilterIterator that checks for is_object in the accept() method.
16

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

Comments

5

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

Comments

0

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

1 Comment

An answer shouldn't be asking a question.
0

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.

Comments

0

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
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.