PHP:在嵌套关联数组中查找键

时间:2013-12-11 21:34:07

标签: php arrays associative-array

我有一种检查密钥是否在嵌套关联数组中的方法:

private function checkKeyIsInArray($dataItemName, $array) {      
    foreach ($array as $key=>$value) {
        if ($key == $dataItemName) return true;
        if (is_array($value)) {
            checkKeyIsInArray($dataItemName, $value);
        }
    }
    return false;
}

无论我包含或不包含哪些键,它始终返回true。这是我的测试数组:

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

拜托,我做错了什么?如果我搜索“reset_time”,则该方法返回true(如我所料);当我搜索“reset_expired”时,该方法也返回true(这是不正确的)。

2 个答案:

答案 0 :(得分:1)

你的方法几乎可行。但问题很少。

  1. Comparsion数值和字符串。在第一轮方法中,0为关键,“email”为值。 0 == 'email'始终返回true。

  2. 调用对象成员函数时应使用$this

  3. 您应该返回递归函数的值。

  4. 你的重写方法。

    class check
        {
    
        private function checkKeyIsInArray($dataItemName, $array)
            {
            foreach ($array as $key => $value)
                {
                // convert $key to string to prevent key type convertion
                if ((string) $key == $dataItemName)
                    return true;
                if (is_array($value))
                // $this added
                // return added
                    return $this->checkKeyIsInArray($dataItemName, $value);
                }
            return false;
            }
    
        public function myCheck($dataItemName, $array)
            {
            return $this->checkKeyIsInArray($dataItemName, $array);
            }
    
        }
    
    $check = new check();
    $array = array(array('reset_time' => 123, 'email' => 123));
    var_dump($check->myCheck('reset_time', $array)); // true
    var_dump($check->myCheck('reset_expired', $array)); // false
    var_dump($check->myCheck('0', $array)); // true
    

答案 1 :(得分:1)

我已经更新了你自己的代码,有一些小问题。请检查。

function checkKeyIsInArray($dataItemName, $array) {      
   foreach ($array as $key=>$value) {
    ## here $key is int and $dataItemName is string so its alway comes true in ur case
    if ("$key" == $dataItemName) {
         return true;
    }
    else if (is_array($value)) {
        $returnvalue=checkKeyIsInArray($dataItemName, $value);
        ## once a matching key found  stop further recursive call
        if($returnvalue==true){
          return true;
        }
    }
  }
   return false;
}