简体   繁体   中英

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.

I hope I explained that well enough :)

You could use a RecursiveArrayIterator and 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 ) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM