开发者

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.


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.


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

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

   return $p;
}


Here is a different approach:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜