简体   繁体   English

PHP array_key_exists并且不为空

[英]PHP array_key_exists and is not empty

Following on from a previous question, I am now using the following function to check if a key exists in a multi-dimensional array... 在上一个问题之后,我现在使用以下函数来检查多维数组中是否存在键...

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) || is_object($v))
            $result = array_key_exists_r($needle, $v);
            if ($result)
            return $result;
        }

        return $result;
    }

I am checking like this... 我正在这样检查...

if (array_key_exists_r("image",$myarray)) {
echo 'Array Key Image Exists';
}

But now I am trying to modify it or the result to check that key is not empty, can I do this inside the function or should I do something with the output of the function? 但是现在我正在尝试修改它或结果以检查键是否为空,我可以在函数内部执行此操作还是应该对函数的输出执行某些操作?

Or should I be using isset instead? 还是应该改用isset?

Whether you do this inside the function or not it's fully up to you. 是否在函数内部执行此操作完全取决于您。 Personally if I did it inside the function I would change its name to something clearer since it doesn't only check if a key exists. 就我个人而言,如果我在函数内执行此操作,我会将其名称更改为更清晰的名称,因为它不仅检查键是否存在。 Anyhow I found a solution within the same function: 无论如何,我在同一函数中找到了一个解决方案:

function array_key_exists_r($needle, $haystack){

    $result = array_key_exists($needle, $haystack);

    if ($result && $haystack[$needle]){
        return $result;
    }


    foreach ($haystack as $v)
    { 
        if (is_array($v) || is_object($v)){
            $result = array_key_exists_r($needle, $v);

            if ($result) {
                return $result;
            }
        }
    } 

    return false;
}

So basically I added a validation on your ifs and that did it also change the default return value to false just in case. 因此,基本上,我在您的ifs上添加了一个验证,并且这样做也将默认返回值更改为false以防万一。 I think it can still be enhanced but this does the job. 我认为它仍然可以增强,但是可以做到。

Try this approach instead. 请尝试这种方法。 Easier! 更轻松!

function array_key_exists_r($needle, $haystack) {
   $found = [];
   array_walk_recursive($haystack, function ($key, $value) use (&$found) {
      # Collect your data here in $found
   });
   return $found;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM