php - How to use a string as an array index path to retrieve a value?
40
Let say I have an array like:
Array
(
[0] => Array
(
[Data] => Array
(
[id] => 1
[title] => Manager
[name] => John Smith
)
)
[1] => Array
(
[Data] => Array
(
[id] => 1
[title] => Clerk
[name] =>
(
[first] => Jane
[last] => Smith
)
)
)
)
I want to be able to build a function that I can pass a string to that will act as the array index path and return the appropriate array value without usingeval()
. Is that possible?
function($indexPath, $arrayToAccess)
{
// $indexPath would be something like [0]['Data']['name'] which would return
// "Manager" or it could be [1]['Data']['name']['first'] which would return
// "Jane" but the amount of array indexes that will be in the index path can
// change, so there might be 3 like the first example, or 4 like the second.
return $arrayToAccess[$indexPath] // <- obviously won't work
}
Answer
Solution:
A Bit later, but... hope helps someone:
Now itens is the part of the array you wanted to.
[]'s
Labs
Answer
Solution:
you might use an array as path (from left to right), then a recursive function:
Answer
Solution:
This is an old question but it has been referenced as this question comes up frequently.
There are recursive functions but I use a reference:
Answer
Solution:
Try the following where $indexPath is formatted like a file path i.e.
e.g. using the data from the question, $indexPath = '1/Data/name/first' would return $value = Jane.
Answer
Solution:
Answer
Solution:
You have to parse indexPath string. Chose some separator (for example "."), read text until "." that would be the first key, then read rest until next, that would be next key. Do that until no more dots.
You ken store key in array. Do foreach loop on this array to get seeked element.
Answer
Solution:
Here is one way to get the job done, if string parsing is the way you want to go.
Answer
Solution:
A
preg_match_all
, cycling through the matched results would give you CLOSE to the result you wanted. You need to be careful with all of the strategies listed here for lost information. For instance, you have to devise some way to ensure that 55 stays as type int and isn't parsed as type string.Answer
Solution:
In addition to AbraCadaver:
Possible use
Example
Resources
https://gist.github.com/rafasashi/0d3ebadf08b8c2976a9d
Answer
Solution:
If you already know the exact array element that you are pulling out why write a function to do it? What's wrong with just