Search code examples
phpmultidimensional-arrayarray-filterarray-walk

PHP searching a multidemisional array by key


I would like to search through a multidimensional array and return the value of the first key found. For example I am working with some geo tools and it returns this array. How can I recursively go through this array and return the first value of any key with the name lat? I tried array_walk but that seems to just return true or false. I tried array_filter but I dont think that is what its for? But I dont know how many sub arrays the array will have, so I need it to just go through each array set until it finds the key Im looking for, return the value and be done.

    array(4) {
  ["bounds"]=>
  array(2) {
    ["northeast"]=>
    array(2) {
      ["lat"]=>
      float(37.8468559)
      ["lng"]=>
      float(-121.891768)
    }
    ["southwest"]=>
    array(2) {
      ["lat"]=>
      float(37.779857)
      ["lng"]=>
      float(-122.027307)
    }
  }
  ["location"]=>
  array(2) {
    ["lat"]=>
    float(37.8215929)
    ["lng"]=>
    float(-121.9999606)
  }
  ["location_type"]=>
  string(11) "APPROXIMATE"
  ["viewport"]=>
  array(2) {
    ["northeast"]=>
    array(2) {
      ["lat"]=>
      float(37.8468559)
      ["lng"]=>
      float(-121.891768)
    }
    ["southwest"]=>
    array(2) {
      ["lat"]=>
      float(37.779857)
      ["lng"]=>
      float(-122.027307)
    }
  }
}

Here is an example of using array_filter. It works, only if I echo the value, but I want to return the value to use it at a different time. But when I do a return, it returns the whole sub array:

        function getLat($k,$v)
        {
        if(is_array($k)){
            foreach($k AS $key => $value)
            {

                if($key == 'lat')
                {

                    echo $value;

                }

            }}
        }

        $test = array_filter($response,'getLat',ARRAY_FILTER_USE_BOTH);

That echos 37.8215929. Which is what I want, but want to return it. When I change echo to return it returns this:

array(1) {
  ["location"]=>
  array(2) {
    ["lat"]=>
    float(37.8215929)
    ["lng"]=>
    float(-121.9999606)
  }
}

Solution

  • Use the use keyword and an anonymous function with array_walk_recursive:

    $return_value = null;
    array_walk_recursive($array, function ($item, $key) use (&$return_value) {
      if($key === "lat") {
        $return_value = $item;
      }
    });
    return $return_value;
    

    Pass a reference (&) to change a variable (in this case $return_value) outside the closure (anonymous function).