检查是否存在“运行时"多维数组键存在 [英] Check if a "run-time" multidimensional array key exists

查看:52
本文介绍了检查是否存在“运行时"多维数组键存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维数组.我需要一个函数来检查指定的键是否存在.

I have a multidimensional array. I need a function that checks if a specified key exists.

让我们拿这个数组

$config['lib']['template']['engine'] = 'setted';

一个函数在我调用它时应该返回真:

A function should return true when I call it with:

checkKey('lib','template','engine');
//> Checks if isset $config['lib']['template']['engine']

请注意,我的数组不仅是 3 维的.即使只有一维,它也应该能够检查:

Note that my array isn't only 3 dimensional. It should be able to check even with only 1 dimension:

checkKey('genericSetting');
//> Returns false becase $c['genericSetting'] isn't setted

目前我正在使用一个糟糕的 eval 代码,我想听听建议 :)

At the moment I am using an awful eval code, I would like to hear suggest :)

推荐答案

function checkKey($array) {
  $args = func_get_args();
  for ($i = 1; $i < count($args); $i++) {
    if (!isset($array[$args[$i]]))
       return false;
    $array = &$array[$args[$i]];
  }
  return true;
}

用法:

checkKey($config, 'lib', 'template', 'engine');
checkKey($config, 'genericSetting');

这篇关于检查是否存在“运行时"多维数组键存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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