简体   繁体   English

在多维数组中找到键=>值,但返回父键?

[英]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 我想获得数组array("chicken" => "notfree")并知道父键是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? 我可以很容易地获得"chicken" => "notfree" ,但是我似乎无法获得父键, $arrIt->key()总是返回null? Any ideas? 有任何想法吗?

You have to set a key value inside the foreach loop, this would be the key of your current location within the array. 您必须在foreach循环中设置一个键值,这将是您在数组中当前位置的键。

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. 您不需要创建迭代器,该迭代器已经将其放置在一个级别上。

Use the two-argument form of foreach , so you get a variable containing the "parent" key: 使用foreach的两个参数形式,这样您将获得一个包含“ parent”键的变量:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM