Home >Backend Development >PHP Tutorial >How to Access Nested Array Values Using String Path Expressions Without eval()?

How to Access Nested Array Values Using String Path Expressions Without eval()?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 03:00:03429browse

How to Access Nested Array Values Using String Path Expressions Without eval()?

Retrieving Array Values Using String Path Expressions

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn