1

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?

Steven
  • 13,250
  • 33
  • 95
  • 147

3 Answers3

1

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.

thepratt
  • 323
  • 1
  • 13
  • That doesn't work http://pastie.org/8333181 if you run that you'll see it returns `"chicken"`, I don't want `"chicken"` I want the parent key (or `1` in this instance). – Steven Sep 17 '13 at 14:43
  • I'm assuming you'd have more than 1 pair inside each array so that is why I placed another foreach inside to demonstrate that you're able to nest these. – thepratt Sep 18 '13 at 09:29
0

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;
    }
}
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • That doesn't work http://pastie.org/8333181 if you run that you'll see it returns `"chicken"`, I don't want `"chicken"` I want the parent key (or `1` in this instance). – Steven Sep 17 '13 at 14:42
0
    $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;

codediesel
  • 43
  • 6