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

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

        )

)

我希望能够构建一个函数,我可以将一个字符串传递给该函数,该函数将充当数组索引路径并返回适当的数组值,而无需使用 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
}

最佳答案

稍后,但是...希望对某人有所帮助:

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

现在 itens 是您想要的数组的一部分。

[]的

实验室

关于php - 如何使用字符串作为数组索引路径来检索值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1677099/

相关文章:

php - 将 curl stdout 捕获到 PHP 中的变量中

PHP 警告:DOMDocument::loadHTML():属性 alt 已重新定义

arrays - 最佳实践 : Print an array in a bash script

javascript - 如何使用 Ramda remove 从对象数组中删除空对象?

javascript - 我试图弄清楚如何更改页面上显示的日期格式

php - 创建评论部分 - 最佳方法?

java - 如何从 REST post 请求中解析 Json 数组

PHP:访问嵌套数组元素的有效方法?

arrays - 用 printf 打印字符指针字符数组?

php - 如何将文本文件中的特定数据导入mysql?