在嵌套关联数组中查找键 [英] Find key in nested associative array

查看:101
本文介绍了在嵌套关联数组中查找键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前几天,我问了一个与此有关的问题,我得到了答案,但它没有达到我想要的效果.这是我遍历多维关联数组,检查键是否在数组中的方法(根据上一个问题的答案):

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;
}

这是我的数组结构:

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.

这篇关于在嵌套关联数组中查找键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆