[英]Is there any way to index an array with a sequence of indexes in a variable in PHP?
Having: an array $a, a variable $indexes = "[\\"level1\\"][\\"level2\\"][\\"level3\\"]"
; 具有:数组$ a,变量
$indexes = "[\\"level1\\"][\\"level2\\"][\\"level3\\"]"
;
Is there any way to access $a["level1"]["level2"]["level3"]
? 有什么方法可以访问
$a["level1"]["level2"]["level3"]
吗?
The situation is that the number of indexes that this function will handle can change. 情况是此函数将处理的索引数可以更改。 So this is the reason the indexes comes in a variable.
因此,这就是索引进入变量的原因。
Hope this simple solution will help you out. 希望这个简单的解决方案能对您有所帮助。
Try this code snippet here 在此处尝试此代码段
<?php
ini_set('display_errors', 1);
//Here we are retrieving levels
$indexes = '["level1"]["level2"]["level3"]';
preg_match_all('/(?<=")[\w]+(?=")/', $indexes,$matches);
$levels=$matches[0];
//this is the sample array
$array=$tempArray=array(
"level1"=>array(
"level2"=>array(
"level3"=>"someValue"
)
)
);
//here we are iterating over levels to get desired output.
foreach($levels as $level)
{
$tempArray=$tempArray[$level];
}
print_r($tempArray);
Firstly, do not use string
for $indexes
, use an array
. 首先,不要将
string
用于$indexes
,而要使用array
。
For simple retrieving, you can use array_reduce
: 为了简单的检索,可以使用
array_reduce
:
$result = array_reduce($indexes, function ($array, $index) {
return isset($array[$index]) ? $array[$index] : null;
}, $array);
Note that value defaults to null
when there is no such index in the array. 请注意,如果数组中没有这样的索引,则值默认为
null
。
Here is working demo . 这是工作演示 。
If you want some more sophisticated stuff, check out a library I wrote some time ago for situations, when you also need to add items to an array and check for the existence: 如果您需要一些更复杂的东西,请查看我一段时间前写的一个库,以了解情况,当您还需要向数组中添加项目并检查是否存在时:
var_dump(isset($array[['foo', 'bar']]));
var_dump($array[['foo', 'bar']]);
$array[['foo', 'bar']] = 'baz';
unset($array[['foo', 'bar']]);
They are all valid usage examples for existence checking, retrieving the element, writing the element and deleting the element respectively. 它们都是用于存在性检查,检索元素,写入元素和删除元素的有效用法示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.