igneosaur
igneosaur

Reputation: 3346

How can I use a php array as a path to target a value in another array?

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.

Upvotes: 4

Views: 1244

Answers (3)

David Amey
David Amey

Reputation: 1411

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

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

   return $p;
}

Upvotes: 3

Sascha Galley
Sascha Galley

Reputation: 16091

Here is a different approach:

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

Upvotes: 0

Glass Robot
Glass Robot

Reputation: 2448

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.

Upvotes: 4

Related Questions