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
185 views
in Technique[技术] by (71.8m points)

PHP Selecting unknown depth of array

I'm going to try to make this as simple as possible. A dot notation string gets sent to a function, so for example, this would be the string.

'user.id' 

Then I explode the dot to give me an array of names

$dotNotation = explode(".", $variable);

And now I need to use these names to select from another variable like so

$row[$dotNotation[0]][$dotNotation[1]]

So this would be

$row['user']['id']

However, I need it to be dynamic, it can be any depth i.e there can be any number of dots. I'm totally stuck on how to achieve this.


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

1 Answer

0 votes
by (71.8m points)

You could just iterate through all the keys and retrieve the value:

function getDotNotationValue($dotNotation, $row) {
   $dotNotationArray = explode(".", $dotNotation);
   foreach($dotNotationArray as $key) {
      $row = $row[$key];
   }
   return $row;
}

$row = ["test1" => ["test2" => ["test3" => "value"]]];
$string = "test1.test2.test3";
echo getDotNotationValue($string, $row);

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

...