phparraysrecursionmultidimensional-arrayfilter

Recursively search a multidimensional array for the parent key of a matched key or value


I am trying to search a multidimensional array, where when I search for a value it should return me its parent key. Array looks like this:

[
  "fruits" => [
     "sweet" => [
       "apple",
       "banana",
     ],
     "citrus" => [
       "lemon",
       "orange",
     ]
   ],
   "vegetables" => [
     "leafy" => [
       "spinach",
       "broccoli",
     ]
   ],
]

I want the function to return leafy when I search for broccoli or if I search for leafy then it should return vegetables but this function always return me null:

function recursiveFind(array $haystack, $needle)
{
    $foundKey = null;
    foreach ($haystack as $key => $value) {        

        if(is_array($value)) {
            if(in_array($needle, $value)){
                return $key;
            } else {
                $foundKey = recursiveFind($value, $needle);
            }
        }

    }
    return $foundKey;
}

One more function I tried is as below, which returns me false always:

function recursiveFind(array $haystack, $needle)
{
        foreach($haystack as $key => $value) {
            $current_key = $key;
            if($needle === $value || (is_array($value) && recursiveFind($value, $needle) !== false)) {
                return $current_key;
            }
        }
        return false;
}

Above function works when there is only second level for example if we remove fruits and vegetable wrappers.


Solution

  • function recursiveFind(array $haystack, $needle)
    {
       foreach($haystack as $key => $data){
            foreach($data as $k=>$v){
                if($needle==$k){
                    return $key;
                }
                if(in_array($needle, $v)){
                    return $k;
                }
            }
        }
        return null;
    }
    

    As per your requirement specified in comments-

     public $needle = 'citrus';
    
    private function recursiveFind($haystack, $prev)
    {
        foreach ($haystack as $key => $data) {
            if (is_array($data) && in_array($this->needle, $data)) {
                return $key;
            }
            if ($this->needle === $key) {
                return $prev;
            }
            if (is_array($data)) {
                $result = $this->recursiveFind($data, $key);
                if ($result != null)
                    return $result;
            }
        }
    
        return null;
    }
    

    And call this like-

    $value = $this->recursiveFind($data, null);
    
    return $value;
    

    Notice that I have declared $needle as a class variable. You can set this field anything you want now.

    Happy Coding :)