How to remove empty values from multidimensional array in PHP?

前端 未结 8 2320
梦如初夏
梦如初夏 2020-12-06 11:47

I\'ve been looking a lot of answers, but none of them are working for me.

This is the data assigned to my $quantities array:

Array(
             


        
8条回答
  •  遥遥无期
    2020-12-06 12:33

    This removes all items with null values recursively on multideminsional arrays. Works on PHP >= 5.6. If you want to remove all "empty" values, replace !is_null($value) with !empty($value).

    function recursivelyRemoveItemsWithNullValuesFromArray(array $data = []): array
    {
        $data = array_map(function($value) {
            return is_array($value) ? recursivelyRemoveItemsWithNullValuesFromArray($value) : $value;
        }, $data);
    
        return array_filter($data, function($value) {
            return !is_null($value);
        });
    }
    

提交回复
热议问题