phpspl

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


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?


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.