dtrotfd1012 2017-11-03 23:02
浏览 294
已采纳

如何检查多维数组中是否存在特定的数组键

if i'm accessing an index like that

$var = $final_Length_Array[1][0]['id'];

how to check whether the "id" key index exist in the array or not.

i tried to use function array_key_exists but it seems to be working only on one dimension array.

i tried it like if(array_key_exists('id',$final_Length_Array)){ but it didn't work

i also tried isset to check whether there is a result or not but it didn't work also if(isset($final_Length_Array[1][0]['id'])){

any help i'll be appreciate it

  • 写回答

1条回答 默认 最新

  • duanqu9292 2017-11-03 23:27
    关注

    Super hacky solution:

    function array_key_exists_recursive($array, $key) {
        return strpos(json_encode($array), "\"" . $key . "\":") !== false;
    }
    

    Better solution:

    $array = ['a' => ['b' => 'c']];
    function array_key_exists_recursive($key, $array) {
        if (array_key_exists($key, $array)) {
            return true;
        }
        foreach($array as $k => $value) {
            if (is_array($value) && array_key_exists_recursive($key, $value)) {
                return true;
            }
        }
        return false;            
    }
    
    var_dump(array_key_exists_recursive('b', $array));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?