Find a key => value in multidimensional array but return parent key? [duplicate]

StackOverflow https://stackoverflow.com/questions/18852698

  •  28-06-2022
  •  | 
  •  

Question

I am trying to loop through an array, and return a key and child array of an array which has a set key => value.

For example...

Let's say I have

array(0 => array("chicken" => "free"), 1 => array("chicken" => "notfree"));

And I want to get the array array("chicken" => "notfree") and know that the parent key is 1

I have the following...

function search($array, $key, $value) {
    $arrIt = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));

    foreach($arrIt as $sub) {
        $subArray = $arrIt->getSubIterator();
        $subKey = $arrIt->key();
        if(isset($subArray[$key]) && $subArray[$key] === $value) {
            return array("key" => $subKey, "array" => iterator_to_array($subArray));
        }
    }
}

I can easily get the "chicken" => "notfree", but I can't seem to get the parent key, $arrIt->key() keeps returning null? Any ideas?

Was it helpful?

Solution

You have to set a key value inside the foreach loop, this would be the key of your current location within the array.

foreach ($array as $key => $value) {
    //$key here is your 0/1
    foreach ($value as $_key => $_value) {
        //the inner pairs
        //e.g. $_key = 'chicken' & $_value = 'free'
    }
}

You don't need to create an iterator, that has already placed it down a level.

OTHER TIPS

Use the two-argument form of foreach, so you get a variable containing the "parent" key:

foreach($arrIt as $parentKey => $sub) {
    ....
    if(isset(...)) {
        return $parentKey;
    }
}
    $parent_key_set = null;
    foreach ($parse as $parent_key => $child) {
        if (array_key_exists($key, $child)) {
            $parent_key_set = $parent_key;
            break;
        }
    }
    

return $parent_key_set;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top