[英]PHP - How to store an arrays keys in an array and use it to later access the value
I want to save off an array of keys and use it like an index to get back to the corresponding value in the original array. 我想保存一个键数组,并像索引一样使用它,以返回到原始数组中的相应值。 Here's an example to illustrate.
这是一个例子来说明。
$myArray = array("foo" => array("bar" => "Hello"));
the manual way to get to "Hello" would be 手动进入“ Hello”的方式是
$helloString = $myArray["foo"]["bar"];
but I want a flexible way to do this for arrays with N number of keys something like 但是我想要一种灵活的方法来对具有N个键的数组执行此操作,例如
$keys = array("foo","bar");
$helloString = $myArray[$keys]; //doesn't work but hopefully shows my intent
Is there a way to do this without using eval()? 有没有不使用eval()的方法?
I guess you could do something like this: 我猜你可以做这样的事情:
<?php
$myArray = array("foo" => array("bar" => "Hello"));
$keys = array("foo","bar");
$item = $myArray;
foreach($keys as $k) {
$item = $item[$k];
}
echo $item; //Hello
?>
Or stick it in a function: 或将其粘贴在函数中:
function getValue($array, $keys) {
foreach($keys as $k)
$array = $array[$k];
return $array;
}
Don't really understand but try : 不太了解,请尝试:
$keys = array("foo","bar");
$helloString = $myArray[$keys[0]][$keys[1]];
You can even try this one also 你甚至可以尝试这个
$myArray = array("foo" => array("bar" => "Hello"));
$keys = array("foo","bar");
function getval($myArray, $keys){
$temp = $myArray[$keys[0]];
if(!is_array($temp)){
return $temp;
}
else
{
array_splice($keys,0,1);
return getval($temp, $keys);
}
}
//Here you go
echo getval($myArray, $keys);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.