Thursday, 30 August 2018

PHP - Choose a value from a two-dimensional array based on the 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 :)

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
    )

0 comments:

Post a Comment