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

编程入门 行业动态 更新时间:2024-10-27 06:23:05
本文介绍了如何使用字符串作为数组索引路径检索值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

让说我有这样一个数组:

阵列(    [0] =>排列        (            [数据] =>排列                (                    [ID] => 1                    [标题] =>经理                    [名] =>约翰·史密斯                )         )    [1] =>排列        (            [数据] =>排列                 (                     [ID] => 1                     [标题] =>书记                     [名] =>                         (                             [首页] =>简                             [最后] =>工匠                         )                 )        ))

我希望能够建立我可以通过一个字符串将作为数组的索引路径,并且不使用的eval()。这可能吗?

函数($ indexPath,$ arrayToAccess){    // $ indexPath会是这样的[0] ['数据'] ['名']这将返回    //经理人或者它可以[1] ['数据'] ['名'] ['第一']这将返回    //简,但会在索引路径数组索引量能    //变化,所以有可能是3,如第一个例子,或4类似的第二个。    返回$ arrayToAccess [$ indexPath] //< - 显然是行不通的}

解决方案

您可以使用数组作为路径(从左至右),那么递归函数:

$指数= {0,'数据','名'};功能的get_value($索引,$ arrayToAccess){   如果(计数($索引)→1)    返回的get_value(array_slice($索引,1),$ arrayToAccess [$索引[0]);   其他    返回$ arrayToAccess [$索引[0]];}

Let say I have an array like:

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

I want to be able to build a function that I can pass a string to that will act as the array index path and return the appropriate array value without using eval(). Is that possible?

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 }

解决方案

you might use an array as path (from left to right), then a recursive function:

$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]]; }

更多推荐

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

本文发布于:2023-10-10 11:28:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1478537.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字符串   如何使用   路径   索引

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!