[英]PHP -> Pick value from two-dimensional array based on key
I need to pick a value based on a specific key from an two-dimensional array, how would I do that? 我需要根据二维数组中的特定键选择一个值,我该怎么做?
I only know the key of the second level in the array in my code, and not in which array key it sits in level 1... 我只知道代码中数组第二级的键,而不知道它位于第一级的哪个数组键...
example: 例:
Array
(
[0] => Array
(
[1] => http://stackoverflow.com/
)
[1] => Array
(
[0] => http://www.google.com
)
[2] => Array
(
[20567] => http://www.yahoo.com
)
)
Now I would like to pick the value of the key 20567 dynamically, I don't know where it sits in level 1, could be 0, 1,2 or any other key. 现在,我想动态地选择键20567的值,我不知道它在级别1中的位置可以是0、1,2,或任何其他键。
I hope I explained that well enough :) 我希望我能解释得足够好:)
You could use a RecursiveArrayIterator and RecursiveIteratorIterator : 您可以使用RecursiveArrayIterator和RecursiveIteratorIterator :
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $key => $value) {
if ($key == 20567) {
var_dump($value);
break;
}
}
Example in a function: 函数示例:
function valueForKey($array, $key) {
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $arrayKey => $arrayValue) {
if ($arrayKey == $key) {
return $arrayValue
}
}
return null;
}
Another option is: (should work) 另一个选择是:(应该起作用)
function getURLbyRedirects($redirectNumber , $array)
{
foreach($array as $lvl => $elems)
{
if(array_key_exists($redirectNumber , $elems))
return $elems[$redirectNumber];
}
return false;
}
By the way , consider using a different structre for this array, something like this: 顺便说一下,考虑为该数组使用不同的结构,如下所示:
Array (
数组(
[0] => Array ( [url] => http://stackoverflow.com/ [redirects] => 2067 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.