出于安全原因,如何使用字符串作为索引路径来访问复杂数组中的特定值,而不依赖 eval() ?

Susan Sarandon
发布: 2024-10-26 17:15:30
原创
784 人浏览过

How can I access specific values in a complex array using a string as an index path without relying on eval() for security reasons?

如何使用字符串作为索引路径访问数组值

如果你有一个结构复杂的数组,你可能会遇到需要使用表示该值路径的字符串来访问特定值。由于潜在的安全漏洞,不建议使用 eval()。相反,可以创建一个可以处理此任务的自定义函数。

考虑以下示例数组:

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

        )

)
登录后复制

您可以建立一个将字符串作为索引路径的函数,并要作为输入访问的数组:

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
}
登录后复制

要实现所需的功能,您可以利用explode()函数:

$paths = explode(":", $indexPath); 
$itens = $myArray;
foreach($paths as $ndx){
    $itens = $itens[$ndx];
}
登录后复制

在此示例中,$pathStr代表输入字符串路径,$myArray 是要访问的数组。此代码迭代 $paths 的元素,即 $indexPath 中用冒号 (:) 分隔的子字符串,并使用当前 $itens 迭代中 $ndx 处的值更新 $itens。

作为结果,$itens 将包含您根据指定的字符串路径从数组中查找的值。这种方法比使用 eval() 更安全、更灵活,因为它不涉及动态执行 PHP 代码。

以上是出于安全原因,如何使用字符串作为索引路径来访问复杂数组中的特定值,而不依赖 eval() ?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!