Home >Backend Development >PHP Tutorial >How to Access Nested Array Values Using String Path Expressions Without eval()?
In programming, it's often necessary to access nested array values using flexible paths. Consider an array structure like the following:
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 ) ) ) )
The task is to write a function that takes a string as input representing an array index path and returns the corresponding value. This avoids using the potentially dangerous eval() function.
Solution
The key to solving this problem lies in breaking down the index path string into individual array keys. This can be achieved using the explode() function.
<code class="php">$pathStr = "0:Data:name"; $paths = explode(":", $pathStr); </code>
With the keys extracted, we can iteratively navigate the array using a loop:
<code class="php">$itens = $myArray; foreach($paths as $ndx){ $itens = $itens[$ndx]; }</code>
In this example, $itens will now contain the value "John Smith".
Therefore, the function to accomplish this task would look like:
<code class="php">function getArrayValueByPath($pathStr, $arrayToAccess) { $paths = explode(":", $pathStr); $itens = $arrayToAccess; foreach($paths as $ndx){ $itens = $itens[$ndx]; } return $itens; }</code>
The above is the detailed content of How to Access Nested Array Values Using String Path Expressions Without eval()?. For more information, please follow other related articles on the PHP Chinese website!