如何删除数组的空值


How to remove empty value of array

我正在寻找一种从数组中删除空值的方法。

如果您看到下面的代码,我将尝试删除在将其附加到模型之前传递的空值。但到目前为止,情况并非如此。

当然,我在询问之前先在网上搜索了一下,所以我知道trim()array_map()以及下面的代码并没有达到预期的效果。

正在寻找解决方案,谢谢!

if(Input::get('addcategorie'))
    {
        $new_cats = array();
        foreach(
            explode(
                ',', Input::get('addcategorie')) as $categorie) 
        {
            $categorie = Categorie::firstOrCreate(array('name' => $categorie));
            foreach($new_cats as $newcat)
            if($newcat == ' ' || $newcat == ' ' || $newcat == ''){
                unset($newcat);
            }
            array_push($new_cats, $categorie->id);
        }
        $workshop->categories()->attach($new_cats); 
    }

只需使用array_filter:

$array = [
    0 => 'Patrick',
    1 => null,
    2 => 'Maciel',
    3 => '&nbsp',
    4 => ' '
];
$filtered = array_filter($array);
$nbsp = array_filter($array, function($element) {
    return $element == '&nbsp' OR  $element == ' ';
});
$clean = array_diff($filtered, $nbsp);

返回为:

array(2) {
  [0]=>
  string(7) "Patrick"
  [2]=>
  string(6) "Maciel"
}

此函数删除所有null、empty和&nbsp

您应该在foreach中对unset使用以下代码:

foreach($new_cats as $key => $newcat) {
    if(yourCondition) {
        unset($new_cats[$key])
    }
}
foreach($new_cats as $newcat_i => $newcat) {
    $newcat = trim($newcat);
    if($newcat == ' ' || $newcat == '') {
        unset($new_cats[$newcat_i]);
    }
}

$new_cats = array_filter(
    $new_cats, function ($value) {
        $value = trim($value);
        return $value != '' && $value != ' ';
    }
);

最终代码为:

if(Input::get('addcategorie')) {
    $new_cats = array();
    foreach(explode(',', Input::get('addcategorie')) as $categorie) {
        $categorie = Categorie::firstOrCreate(array('name' => $categorie));
        array_push($new_cats, $categorie->id);
    }
    $new_cats = array_filter(
        $new_cats, function ($value) {
            $value = trim($value);
            return $value != '' && $value != ' ';
        }
    );
    $workshop->categories()->attach($new_cats);
}