PHP:测试多维数组中是否存在单元格

发布于 2024-10-10 03:35:53 字数 421 浏览 0 评论 0原文

我有一个具有多个维度的数组,并且我想测试单元格是否存在。

下面的级联方法肯定是一种安全的方法:

if (array_key_exists($arr, 'dim1Key'))  
  if (array_key_exists($arr['dim1Key'], 'dim2Key'))  
    if (array_key_exists($arr['dim1Key']['dim2Key'], 'dim3Key'))  
      echo "cell exists";  

但是有更简单的方法吗?

我将详细介绍这一点:

  1. 我可以在一条语句中执行此检查吗?
  2. 我必须使用 array_key_exist 还是可以使用 isset 之类的东西?我什么时候使用它们以及为什么?

I have an array with numerous dimensions, and I want to test for the existence of a cell.

The below cascaded approach, will be for sure a safe way to do it:

if (array_key_exists($arr, 'dim1Key'))  
  if (array_key_exists($arr['dim1Key'], 'dim2Key'))  
    if (array_key_exists($arr['dim1Key']['dim2Key'], 'dim3Key'))  
      echo "cell exists";  

But is there a simpler way?

I'll go into more details about this:

  1. Can I perform this check in one single statement?
  2. Do I have to use array_key_exist or can I use something like isset? When do I use each and why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

对不⑦ 2024-10-17 03:35:53

isset() 是规范的测试方法,即使对于多维数组也是如此。除非您需要确切地知道缺少哪个维度,否则类似的内容

isset($arr[1][2][3])

是完全可以接受的,即使 [1][2] 元素不存在(3 可以除非 1 和 2 存在,否则就不存在)。

但是,如果您有

$arr['a'] = null;

后续

isset($arr['a']); // false
array_key_exists('a', $arr); // true

评论:

也许这个类比会有所帮助。将 PHP 变量(实际变量、数组元素等)视为一个纸板箱:

  • isset() 查看盒子内部并确定盒子的内容是否可以类型转换为某些内容那是“不为空”。它不关心盒子是否存在 - 它只关心盒子的内容。如果盒子不存在,那么它显然不能容纳任何东西。
  • array_key_exists() 检查框本身是否存在。盒子里的东西无关紧要,它正在检查纸板的痕迹。

isset() is the cannonical method of testing, even for multidimensional arrays. Unless you need to know exactly which dimension is missing, then something like

isset($arr[1][2][3])

is perfectly acceptable, even if the [1] and [2] elements aren't there (3 can't exist unless 1 and 2 are there).

However, if you have

$arr['a'] = null;

then

isset($arr['a']); // false
array_key_exists('a', $arr); // true

comment followup:

Maybe this analogy will help. Think of a PHP variable (an actual variable, an array element, etc...) as a cardboard box:

  • isset() looks inside the box and figures out if the box's contents can be typecast to something that's "not null". It doesn't care if the box exists or not - it only cares about the box's contents. If the box doesn't exist, then it obviously can't contain anything.
  • array_key_exists() checks if the box itself exists or not. The contents of the box are irrelevant, it's checking for traces of cardboard.
葬シ愛 2024-10-17 03:35:53

我遇到了同样的问题,除了我需要它来处理一些 Drupal 的东西。我还需要检查对象是否包含项目和数组。这是我编写的代码,它是一个递归搜索,用于查看对象是否包含值以及数组。认为有人可能会发现它有用。

function recursiveIsset($variable, $checkArray, $i=0) {
    $new_var = null;
    if(is_array($variable) && array_key_exists($checkArray[$i], $variable))
        $new_var = $variable[$checkArray[$i]];
    else if(is_object($variable) && array_key_exists($checkArray[$i], $variable))
        $new_var = $variable->$checkArray[$i];
    if(!isset($new_var))
        return false;

    else if(count($checkArray) > $i + 1)
        return recursiveIsset($new_var, $checkArray, $i+1);
    else
        return $new_var;
}

使用:例如

recursiveIsset($variables, array('content', 'body', '#object', 'body', 'und'))

在我的例子中,在drupal中,以下变量存在,

$variables['content']['body']['#object']->body['und']

请注意,仅仅因为“#object”被称为对象并不意味着它就是对象。如果该位置存在,我的递归搜索也会返回 true

$variables->content->body['#object']->body['und']

I was having the same problem, except i needed it for some Drupal stuff. I also needed to check if objects contained items as well as arrays. Here's the code I made, its a recursive search that looks to see if objects contain the value as well as arrays. Thought someone might find it useful.

function recursiveIsset($variable, $checkArray, $i=0) {
    $new_var = null;
    if(is_array($variable) && array_key_exists($checkArray[$i], $variable))
        $new_var = $variable[$checkArray[$i]];
    else if(is_object($variable) && array_key_exists($checkArray[$i], $variable))
        $new_var = $variable->$checkArray[$i];
    if(!isset($new_var))
        return false;

    else if(count($checkArray) > $i + 1)
        return recursiveIsset($new_var, $checkArray, $i+1);
    else
        return $new_var;
}

Use: For instance

recursiveIsset($variables, array('content', 'body', '#object', 'body', 'und'))

In my case in drupal this ment for me that the following variable existed

$variables['content']['body']['#object']->body['und']

due note that just because '#object' is called object does not mean that it is. My recursive search also would return true if this location existed

$variables->content->body['#object']->body['und']
呆橘 2024-10-17 03:35:53

对于快速的单行,您可以使用 has 方法 https://github.com/minwork/array" rel="nofollow noreferrer">这个数组库:

Arr::has('dim1Key.dim2Key.dim3Key')

最大的好处是你可以使用点表示法来指定数组键,这使得事情变得更简单、更优雅。

此外,此方法对于 null 值将按预期工作,因为它内部使用 array_key_exists

For a fast one liner you can use has method from this array library:

Arr::has('dim1Key.dim2Key.dim3Key')

Big benefit is that you can use dot notation to specify array keys which makes things simpler and more elegant.

Also, this method will work as expected for null value because it internally uses array_key_exists.

断念 2024-10-17 03:35:53

如果您想检查 $arr['dim1Key']['dim2Key']['dim3Key'],为了安全起见,您需要检查 dim3Key 之前是否存在所有数组。然后您可以使用array_key_exists

所以,是的,有一种更简单的方法,使用单个 if 语句,如下所示:

if (isset($arr['dim1Key']['dim2Key']) &&
    array_key_exists('dim3Key', $arr['dim1Key']['dim2Key'])) ...

If you want to check $arr['dim1Key']['dim2Key']['dim3Key'], to be safe you need to check if all arrays exist before dim3Key. Then you can use array_key_exists.

So yes, there is a simpler way using one single if statement like the following:

if (isset($arr['dim1Key']['dim2Key']) &&
    array_key_exists('dim3Key', $arr['dim1Key']['dim2Key'])) ...
一世旳自豪 2024-10-17 03:35:53

我更喜欢创建如下所示的辅助函数:

function my_isset_multi( $arr,$keys ){
    foreach( $keys as $key ){
        if( !isset( $arr[$key] ) ){
            return false;
        }
        $arr = $arr[$key];
    }
    return $arr;
}

然后在我的代码中,我首先使用上面的函数检查数组,如果它不返回 false,它将返回数组本身。

想象一下你有这样的数组:

$arr = array( 'sample-1' => 'value-1','sample-2' => 'value-2','sample-3' => 'value-3' );

你可以这样写:

$arr = my_isset_multi( $arr,array( 'sample-1','sample-2','sample-3' ) );

if( $arr ){
    //You can use the variable $arr without problems
}

函数 my_isset_multi 将检查数组的每个级别,如果未设置键,它将返回 false。

I prefer creating a helper function like the following:

function my_isset_multi( $arr,$keys ){
    foreach( $keys as $key ){
        if( !isset( $arr[$key] ) ){
            return false;
        }
        $arr = $arr[$key];
    }
    return $arr;
}

Then in my code, I first check the array using the function above, and if it doesn't return false, it will return the array itself.

Imagine you have this kind of array:

$arr = array( 'sample-1' => 'value-1','sample-2' => 'value-2','sample-3' => 'value-3' );

You can write something like this:

$arr = my_isset_multi( $arr,array( 'sample-1','sample-2','sample-3' ) );

if( $arr ){
    //You can use the variable $arr without problems
}

The function my_isset_multi will check for every level of the array, and if a key is not set, it will return false.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文