Laravel |从关联数组中过滤空值

Laravel | Filter null values from an associative array

我有一个这样的关联数组:

 $myarray = array(
                'key1' => 'value1'
                'key2' => 'value1','value2','value3', null ,'value4'
                 null
                'key4' => null ,'value2','value3', null
                'key5'
                 null
                );

我想删除空值,我试过这个:

$collection = collect($myarray);

            $filtered = $collection->filter(function ($value, $key) {
                return $value != null;
            });

结果是这样的:

     $myarray = array(
                'key1' => 'value1'
                'key2' => 'value1','value2','value3', null ,'value4'
                'key4' => null ,'value2','value3', null
                'key5'
                );

但我想要的结果是这样的:

     $myarray = array(
                'key1' => 'value1'
                'key2' => 'value1','value2','value3','value4'
                 null
                'key4' => 'value2','value3'
                'key5'
                 null
                );

我该怎么做?

PS:我正在使用 Laravel 5.4.36

您的代码从顶级数组中删除了 null 个值。您的“期望结果”从 嵌套 数组中删除 null 值。

试试这个:

foreach ($myarray as $key => $value) {
    if (is_null($key) || !is_array($value)) {
        continue;
    }

    $myarray[$key] = array_filter($value);
}