How to remove empty values from multidimensional array in PHP?

前端 未结 8 2337
梦如初夏
梦如初夏 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:28

    Not sure if this is exactly what your looking for.

    function array_remove_null($array) {
        foreach ($array as $key => $value)
        {
            if(is_null($value))
                unset($array[$key]);
            if(is_array($value))
                $array[$key] = array_remove_null($value);
        }
        return $array;
    }
    

    Update (corrections):

    function array_remove_null($array) {
        foreach ($array as $key => $value)
        {
            if(is_null($value))
                unset($array[$key]);
            if(is_string($value) && empty($value))
                unset($array[$key]);
            if(is_array($value))
                $array[$key] = array_remove_null($value);
            if(isset($array[$key]) && count($array[$key])==0)
                unset($array[$key]);
        }
        return $array;
    }
    

    I'm sure better checking and making this more robust might help the solution.

提交回复
热议问题