Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an issue in accessing the array in php.

$path  = "['a']['b']['c']";
$value = $array.$path;

In the above piece of code I have an multidimensional array named $array.

$path is a dynamic value which I would get from database.

Now I want to retrieve the value from $array using $path but I am not able to.

$value = $array.$path

returns me

Array['a']['b']['c']

rather than the value.

I hope I have explained my question properly.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
278 views
Welcome To Ask or Share your Answers For Others

1 Answer

You have two options. First (evil) if to use eval() function - i.e. interpret your string as code.

Second is to parse your path. That will be:

//$path = "['a']['b']['c']";
preg_match_all("/['(.*?)']/", $path, $rgMatches);
$rgResult = $array;
foreach($rgMatches[1] as $sPath)
{
   $rgResult=$rgResult[$sPath];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...