4

I want to access a specific array's property by using a separate array as the path. The problem is the property in question may be at any depth. Here's an example...

I have the associative array of data:

$data = array(
    '1' => 'somethings_value',

    '2' => 'another_value',

    '3' => array(
        '1' => 'deeper_value',
    ),
);

Now I want to access one of these values but using another array that will dictate the path to them (through the keys). So say I had a path array like this:

$path = array('3', '1');

Using that $path array I would want to get to the value $data[3][1] (which would be the string 'deeper_value').

The problem is that the value to access may be at any depth, for example I could also get a path array like this:

$path = array('1');

Which would get the string value 'somethings_value'. I hope the problem is clear now.

So the question is, how do I somehow loop though this path array in order to use its values as keys to target a value located in a target array?

Thanks!

EDIT: It might be worth noting that I have used numbers (albeit in quotes) as the keys for the data array for ease of reading, but the keys in my real problem are actually strings.

3 Answers 3

4

A simple loop should work:

Update: sorry did check my code

foreach($path as $id) 
{
    $data = $data[$id];
}

echo $data;

Result:

deeper_value

This will overwrite the $data array so you might want to make a copy of $data first like David did in his example.

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

4 Comments

You wouldn't be able to access $data[3][1] with this method.
I'm not sure of what I'm about to say, but are you sure that foreach will always take the $id in the correct order? That's not the case in Java, for example.
@Oltarus: I'm sure that php's arrays always have a well-defined order that foreach respects, and that the order defaults to the order of insertion... but I can't find a reference!
@grossvogel Ok, Big Bird, just checking!
3

It's not the greatest code, but should work:

function getValue($pathArray, $data)
{
   $p = $data;
   foreach ($pathArray as $i)
   {
     $p = $p[$i];
   }

   return $p;
}

1 Comment

You can't access $data inside a function unless you use the global keyword. Since global is lame, you should pass $data as a function parameter, which also saves you from having to explicitly create a copy.
0

Here is a different approach:

while($d = array_shift($path))
    $data = $data[$d];

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.