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

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

php - Access array using dynamic path

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

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

1 Answer

0 votes
by (71.8m points)

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];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...