简体   繁体   English

如何删除多维数组中的空值?

[英]How to remove null values in multi-dimensional array?

I want to remove null values from this array.我想从这个数组中删除空值。

Array(
    [0] => Array( [fcmToken] => 123 )
    [1] => Array( [fcmToken] => )
    [2] => Array( [fcmToken] => 789 )
)

Expected Results预期成绩

Array(
    [0] => Array( [fcmToken] => 123 )
    [1] => Array( [fcmToken] => 789 )
)

Here we are using foreach to iterate over values and using $value for non-empty $value["fcmToken"]这里我们使用foreach来迭代值并使用$value来表示non-empty $value["fcmToken"]

$result=array();
foreach($array as $key => $value)
{
    if(!empty($value["fcmToken"]))
    {
        $result[]=$value;
    }
}

print_r($result);

Output:输出:

Array
(
    [0] => Array
        (
            [fcmToken] => dfqVhqdqhpk
        )

    [1] => Array
        (
            [fcmToken] => dfgdfhqdqhpk
        )

)

Use array_filter with a callback:array_filter与回调一起使用:

$r = array_filter($array, function($v) { return !empty($v['fcmToken']); });

For checking exactly null :为了检查完全null

$r = array_filter($array, function($v) { return !is_null($v['fcmToken']); });

The best and easy single line solution for filter multidimensional array like below.过滤多维数组的最佳且简单的单行解决方案,如下所示。

$aryMain = array_filter(array_map('array_filter', $aryMain));

I hope this solution is work for you.我希望这个解决方案对你有用。 for more detail please visit below link.欲了解更多详情,请访问以下链接。

PHP: remove empty array strings in multidimensional array PHP:删除多维数组中的空数组字符串

You need to do it using array_map , array_filter and array_values .您需要使用array_maparray_filterarray_values Check below code :检查以下代码:

$entry = array(
    array("fcmToken" => 'dfqVhqdqhpk'),
    array("fcmToken" => ''),
    array("fcmToken" => 'dfgdfhqdqhpk'),
);
echo "<pre>";
$entry = array_values(array_filter(array_map('array_filter', $entry)));
print_r($entry);

Danger!危险! Do not trust empty() when dealing with numbers (or number-ish) values that could be zero!!!在处理可能为零的数字(或数字-ish)值时,不要相信empty() !!! The same is true with using array_filter without a specific filtering parameter (as several answers on this page are using).使用不带特定过滤参数的array_filter也是如此(因为此页面上的几个答案正在使用)。

Look at how you can get the wrong output:看看如何得到错误的输出:

Bad Method:坏方法:

$array = array(
    array("fcmToken" => '0'),
    array("fcmToken" => 123),
    array("fcmToken" => ''),
    array("fcmToken" => 789),
    array("fcmToken" => 0)
);

$result=array();                         // note, this line is unnecessary
foreach($array as $key => $value){       // note, $key is unnecessary
    if(!empty($value["fcmToken"])){      // this is not a reliable method
        $result[]=$value;
    }
}
var_export($result);

Output:输出:

array (
  0 => 
  array (
    'fcmToken' => 123,
  ),
  1 => 
  array (
    'fcmToken' => 789,
  ),
)

The zeros got swallowed up!零被吞没了!


This is how it should be done:应该这样做:

Instead, you should use strlen() to check the values:相反,您应该使用strlen()来检查值:

Method #1: foreach()方法#1:foreach()

foreach($array as $sub){
    if(strlen($sub["fcmToken"])){
        $result[]=$sub;
    }
}
var_export($result);

Method #2: array_filter() w/ anonymous function and array_values() for consistency方法 #2: array_filter()带有匿名函数和array_values()以保持一致性

var_export(array_values(array_filter($array,function($a){return strlen($a['fcmToken']);})));

Output for either method:任一方法的输出:

array (
  0 => 
  array (
    'fcmToken' => '0',
  ),
  1 => 
  array (
    'fcmToken' => 123,
  ),
  2 => 
  array (
    'fcmToken' => 789,
  ),
  3 => 
  array (
    'fcmToken' => 0,
  ),
)

Demonstration of bad method and two good methods . 演示坏方法和两种好方法

Use this recursive function which iterates over any subarray and remove all elements with a null-value.使用此递归函数迭代任何子数组并删除所有具有空值的元素。

function removeNullValues ($array) {
    foreach ($array as $key => $entry) {
        if (is_array($entry)) {
            $array[$key] = removeNullValues($entry);
            if ($array[$key] === []) {
                unset($array[$key]);
            }
        } else {
            if ($entry === null) {
                unset($array[$key]);
            }
        }
    }

    return $array;
}

尝试使用 array_map() 将过滤器应用于数组中的每个数组。

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

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