如何使用字符串作为数组索引路径来检索值?

Cha*_*les 9 php arrays

假设我有一个类似的数组:

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

        )

)
Run Code Online (Sandbox Code Playgroud)

我希望能够构建一个函数,我可以传递一个字符串,作为数组索引路径,并返回适当的数组值而不使用eval().那可能吗?

function($indexPath, $arrayToAccess)
{
    // $indexPath would be something like [0]['Data']['name'] which would return 
    // "Manager" or it could be [1]['Data']['name']['first'] which would return 
    // "Jane" but the amount of array indexes that will be in the index path can 
    // change, so there might be 3 like the first example, or 4 like the second.

    return $arrayToAccess[$indexPath] // <- obviously won't work
}
Run Code Online (Sandbox Code Playgroud)

小智 17

稍后,但......希望能帮到某人:

// $pathStr = "an:string:with:many:keys:as:path";
$paths = explode(":", $pathStr); 
$itens = $myArray;
foreach($paths as $ndx){
    $itens = $itens[$ndx];
}
Run Code Online (Sandbox Code Playgroud)

现在itens是你想要的数组的一部分.

[]的

实验室


man*_*nji 10

您可以使用数组作为路径(从左到右),然后使用递归函数:

$indexes = {0, 'Data', 'name'};

function get_value($indexes, $arrayToAccess)
{
   if(count($indexes) > 1) 
    return get_value(array_slice($indexes, 1), $arrayToAccess[$indexes[0]]);
   else
    return $arrayToAccess[$indexes[0]];
}
Run Code Online (Sandbox Code Playgroud)