array_key_exists is not working

给你一囗甜甜゛ 提交于 2019-11-26 23:01:41
halfdan

array_key_exists does NOT work recursive (as Matti Virkkunen already pointed out). Have a look at the PHP manual, there is the following piece of code you can use to perform a recursive search:

<?php
function array_key_exists_r($needle, $haystack)
{
    $result = array_key_exists($needle, $haystack);
    if ($result) return $result;
    foreach ($haystack as $v) {
        if (is_array($v)) {
            $result = array_key_exists_r($needle, $v);
        }
        if ($result) return $result;
    }
    return $result;
}

array_key_exists doesn't work on multidimensionaml arrays. if you want to do so, you have to write your own function like this:

function array_key_exists_multi($n, $arr) {
      foreach ($arr as $key=>$val) {
        if ($n===$key) {
          return $key;
        }
        if (is_array($val)) {
          if(multi_array_key_exists($n, $val)) {
            return $key . ":" . array_key_exists_multi($n, $val);
          }
        }
      }
  return false;
}

this returns false if the key isn't found or a string containing the "location" of the key in that array (like 2:23:test) if it's found.

$test_found = false;
array_walk_recursive($arr,
                     function($v, $k) use (&$test_found)
                     {
                         $test_found |= ($k == 'test');
                     });

This requires PHP 5.3 or later.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!