php 如何检查多维数组是否为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18401584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 17:29:37  来源:igfitidea点击:

How to check if a multidimensional array is empty or not?

phparraysmultidimensional-array

提问by Fizzix

Basically, I have a multidimensional array, and I need to check whether or not it is simply empty, or not.

基本上,我有一个多维数组,我需要检查它是否只是空的。

I currently have an ifstatement trying to do this with:

我目前有一份if声明试图通过以下方式执行此操作:

if(!empty($csv_array)) 
{   
    //My code goes here if the array is not empty
}

Although, that if statementis being activated whether the multidimensional array is empty or not.

虽然,if statement无论多维数组是否为空,它都会被激活。

This is what the array looks like when empty:

这是数组空时的样子:

Array
(
    [0] => Array
        (
        )

)

This is what the array looks like when it has a few elements in it:

当数组中有几个元素时,它是这样的:

Array
(
    [0] => Array
        (
        )

    [1] => Array
        (
            [1] => question1
            [2] => answer1
            [3] => answer2
            [4] => answer3
            [5] => answer4
        )

    [2] => Array
        (
            [1] => question2
            [2] => answer1
            [3] => answer2
            [4] => answer3
            [5] => answer4
        )

    [3] => Array
        (
            [1] => question3
            [2] => answer1
            [3] => answer2
            [4] => answer3
            [5] => answer4
        )

)

My array elements always start at 1, and not 0. Long story why, and no point explaining since it is off-topic to this question.

我的数组元素总是从 1 开始,而不是 0。长话短说为什么,没有必要解释,因为它与这个问题无关。

If needed, this is the code that is creating the array. It is being pulled from an uploaded CSV file.

如果需要,这是创建数组的代码。它是从上传的 CSV 文件中提取的。

$csv_array = array(array());
if (!empty($_FILES['upload_csv']['tmp_name'])) 
{
    $file = fopen($_FILES['upload_csv']['tmp_name'], 'r');
}

if($file)
{
    while (($line = fgetcsv($file)) !== FALSE) 
    {
        $csv_array[] = array_combine(range(1, count($line)), array_values($line));
    }

    fclose($file);
}

So in conclusion, I need to modify my if statementto check whether the array is empty or not.

所以总而言之,我需要修改 myif statement以检查数组是否为空。

Thanks in advance!

提前致谢!

采纳答案by Dipesh Parmar

So simply check for if the first key is present in array or not.

所以只需检查数组中是否存在第一个键。

Example

例子

if(!empty($csv_array[1])) 
{   
    //My code goes here if the array is not empty
}

回答by billyonecan

You can filter the array, by default this will remove all empty values. Then you can just check if it's empty:

您可以过滤数组,默认情况下这将删除所有空值。然后你可以检查它是否为空:

$filtered = array_filter($csv_array);
if (!empty($filtered)) {
  // your code
}

Note: This will work with the code posted in your question, if you added another dimension to one of the arrays which was empty, it wouldn't:

注意:这将适用于您的问题中发布的代码,如果您向其中一个空数组添加了另一个维度,则不会:

$array = array(array()); // empty($filtered) = true;
$array = array(array(array())); // empty($filtered) = false;

回答by myol

If you don't know the structure of the multidimensional array

如果你不知道多维数组的结构

public function isEmpty(array $array): bool
{
    $empty = true;

    array_walk_recursive($array, function ($leaf) use (&$empty) {
        if ($leaf === [] || $leaf === '') {
            return;
        }

        $empty = false;
    });

    return $empty;
}

Just keep in mind all leaf nodes will be parsed.

请记住,所有叶节点都将被解析。

回答by shadowdroid

just to be on the save side you want it to remove the empty lines ? or do you want to return if any array is empty ? or do you need a list which positions are empty ?

只是为了在保存方面,您希望它删除空行吗?或者如果任何数组为空,你想返回吗?或者你需要一个列表,哪些职位是空的?

this is just a thought and !!! not tested !!!

这只是一个想法和!!!未测试!!!

/**
 * multi array scan 
 * 
 * @param $array array
 * 
 * @return bool
 */
function scan_array($array = array()){
  if (empty($array)) return true;

  foreach ($array as $sarray) {
    if (empty($sarray)) return true;
  } 

  return false;
}

回答by JFs

Combine array_filter()and array_map()for result. ( Result Test)

结合array_filter()array_map()为结果。(结果测试)

<?php
    $arrayData = [
        '0'=> [],
        '1'=> [
            'question1',
            'answer1',
            'answer2',
            'answer3',
            'answer4'
        ],
        '2'=> [
            'question1',
            'answer1',
            'answer2',
            'answer3',
            'answer4'
        ]
    ];

    $arrayEmpty = [
        '0' => [],
        '1' => [
            '1' => '',
            '2' => '',
            '3' => ''
        ]
    ];

    $resultData = array_filter(array_map('array_filter', $arrayData));
    $resultEmpty = array_filter(array_map('array_filter', $arrayEmpty));

    var_dump('Data', empty($resultData));
    var_dump('Empty', empty($resultEmpty));

回答by RunningAdithya

You can use array_push to avoid this situation,

您可以使用 array_push 来避免这种情况,

$result_array = array();

array_push($result_array,$new_array);

array_push($result_array,$new_array);

refer array_push

参考array_push

Then you can check it using if (!empty($result_array)) { }

然后你可以使用 if (!empty($result_array)) { } 检查它