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

Linda Hamilton
Release: 2024-10-26 03:00:03
Original
337 people have browsed it

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
                         )
                 )

        )

)
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!