简体   繁体   中英

Find key in nested associative array

The other day I asked a question related to this, and I got an answer, but it did not do what I wanted. Here is the method I have for traversing a multidimensional associative array, checking whether a key is in the array (from the answer to my previous question):

private function checkKeyIsInArray($dataItemName, $array)
{
    foreach ($array as $key => $value)
    {
        // convert $key to string to prevent key type convertion
        echo '<pre>The key: '.(string) $key.'</pre>';

        if ((string)$key == $dataItemName)
            return true;

        if (is_array($value))
            return $this->checkKeyIsInArray($dataItemName, $value);

    }
    return false;
}

Here is my array stucture:

Array (
    [0] => Array ( [reset_time] => 2013-12-11 22:24:25 )
    [1] => Array ( [email] => someone@example.com )
)

The method traverses the first array branch, but not the second. Could someone explain why this might be the case please? It seems I am missing something.

The problem is that you return whatever the recursive call returns, regardless of whether it succeeded or failed. You should only return if the key was found during the recursion, otherwise you should keep looping.

private function checkKeyIsInArray($dataItemName, $array)
{
    foreach ($array as $key => $value)
        {
            // convert $key to string to prevent key type convertion
            echo '<pre>The key: '.(string) $key.'</pre>';

            if ((string)$key == $dataItemName)
                return true;

            if (is_array($value) && $this->checkKeyIsInArray($dataItemName, $value))
                return true;

        }
    return false;
}

BTW, why is this a non-static function? It doesn't seem to need any instance properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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