1

If I have an array like this:

$array = array('something'=>array('more'=>array('id'=> 34)));

Then print_r($array['something']['more']['id'] works fine.

But say the key names might change but the structure wont. How could I reference the same values without knowing the names?

I thought maybe print_r($array[0][1][2] might work, but of course those keys don't exist.

1

4 Answers 4

3

You can use a foreach statement. Use a recursive function to handle nested arrays (untested):

public function iterateNestedArray($array) {
    if (is_array($array)) {
        foreach ($array as $key => $value) {
            print_r(iterateNestedArray($value));
        }
    }
    else {
        return $array;
    }
}

You might consider implementing this function with a second argument to pass a callback function, rather than just print_ring every value.

Sign up to request clarification or add additional context in comments.

Comments

0

There are multiple possibilities.

You could use arrayiterator or simply foreach. Perhaps even array_values could be your solution.

Comments

0

you can do a straight loop with foreach, although it's fairly ugly:

foreach ( $grandparent as $gpkey => $parent ) {
    foreach ( $parent as $pkey => $child ) {
        foreach ( $child as $ckey => $value ) {
            print $gpkey . " - " . $pkey . " - " . $ckey . " = " . $value;
        }
    }
}

Or you can get the list of keys with array_keys():

$keys = array_keys($array);
for ( $i=0, $imax=count($keys); $i<$imax; $i++ ) {
    print $key . " = " . $array[$key];
}

Comments

-1

You can use reset(), next() and end() as always

$array = array('something'=>array('more'=>array('id'=> 34)));
echo reset(reset(reset($array)));

1 Comment

-1 This code spits E_STRICT errors. reset accepts a reference, therefore reset(reset()) is invalid (references must be variables; expressions, like function calls, are not accepted).

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.