如何检查多维数组是否只包含空值?

时间:2022-02-18 13:36:56

I looked around and can't quite find the answer for this, so I'm wondering if I contain an array such as this..

我四处看了看,找不到答案,所以我想知道我是否包含这样的数组。

$array['foo']['bar'][1] = '';
$array['foo']['bar'][2] = '';
$array['foo']['bar'][3] = '';
$array['foo']['bar'][4] = '';

How can I check if all the values are empty? I tried doing the following:

如何检查所有值是否为空?我试着做以下事情:

if (empty($array['foo']['bar'])) {
    // Array empty
}

But as expected that didn't work.

但正如预期的那样,这行不通。

How can I do this?

我该怎么做呢?

3 个解决方案

#1


3  

If you wanted to check to see if all of the values where populated you can use

如果您想要查看填充的所有值是否都可以使用

 if(call_user_func_array("isset", $array['foo']['bar']))

For what you want to do though you could use array reduce with a closure

对于您想要做的事情,您可以使用带有闭包的数组reduce

 if(array_reduce($array, function(&$res, $a){if ($a) $res = true;}))

Note this will only work in php 5.3+

注意,这只会在php 5.3+中使用。

#2


1  

$array['foo']['bar'] isn't empty because it's actually array(1=>'',2=>'',3=>'',4=>'').

数组美元[“foo”]['酒吧']并不是空的,因为它实际上是数组(1 = >”,2 = >”,3 = > ",4 = > ")。

You would need to do a foreach loop on it to check if it is indeed all empty.

您需要对它执行一个foreach循环,以检查它是否确实是空的。

$arr_empty = true;
foreach ($array['foo']['bar'] as $arr) {
    if (!empty($arr)) {
        $arr_empty = false;
    }
}
//$arr_empty is now true or false based on $array['foo']['bar']

#3


1  

A short alternative would be:

一个简短的替代方案是:

if (empty(implode($array['foo']['bar']))) {
  // is empty
}

Note that some single values may be considered as empty. See empty().

注意,有些值可能被认为是空的。看到空的()。

#1


3  

If you wanted to check to see if all of the values where populated you can use

如果您想要查看填充的所有值是否都可以使用

 if(call_user_func_array("isset", $array['foo']['bar']))

For what you want to do though you could use array reduce with a closure

对于您想要做的事情,您可以使用带有闭包的数组reduce

 if(array_reduce($array, function(&$res, $a){if ($a) $res = true;}))

Note this will only work in php 5.3+

注意,这只会在php 5.3+中使用。

#2


1  

$array['foo']['bar'] isn't empty because it's actually array(1=>'',2=>'',3=>'',4=>'').

数组美元[“foo”]['酒吧']并不是空的,因为它实际上是数组(1 = >”,2 = >”,3 = > ",4 = > ")。

You would need to do a foreach loop on it to check if it is indeed all empty.

您需要对它执行一个foreach循环,以检查它是否确实是空的。

$arr_empty = true;
foreach ($array['foo']['bar'] as $arr) {
    if (!empty($arr)) {
        $arr_empty = false;
    }
}
//$arr_empty is now true or false based on $array['foo']['bar']

#3


1  

A short alternative would be:

一个简短的替代方案是:

if (empty(implode($array['foo']['bar']))) {
  // is empty
}

Note that some single values may be considered as empty. See empty().

注意,有些值可能被认为是空的。看到空的()。