Recursively remove empty elements and subarrays from a multi-dimensional array

后端 未结 6 2072
暖寄归人
暖寄归人 2020-11-27 19:19

I can\'t seem to find a simple, straight-forward solution to the age-old problem of removing empty elements from arrays in PHP.

My input array may look like this: <

6条回答
  •  半阙折子戏
    2020-11-27 19:32

    array_filter() is not type-sensitive by default. This means that any zero-ish, false-y, null, empty values will be removed. My links to follow will demonstrate this point.

    The OP's sample input array is 2-dimensional. If the data structure is static then recursion is not necessary. For anyone who would like to filter the zero-length values from a multi-dimensional array, I'll provide a static 2-dim method and a recursive method.

    Static 2-dim Array: This code performs a "zero-safe" filter on the 2nd level elements and then removes empty subarrays: (See this demo to see this method work with different (trickier) array data)

    $array=[
        ['Name'=>'','EmailAddress'=>'']
    ];   
    
    var_export(
        array_filter(  // remove the 2nd level in the event that all subarray elements are removed
            array_map(  // access/iterate 2nd level values
                function($v){
                    return array_filter($v,'strlen');  // filter out subarray elements with zero-length values
                },$array  // the input array
            )
        )
    );
    

    Here is the same code as a one-liner:

    var_export(array_filter(array_map(function($v){return array_filter($v,'strlen');},$array)));
    

    Output (as originally specified by the OP):

    array (
    )
    

    *if you don't want to remove the empty subarrays, simply remove the outer array_filter() call.


    Recursive method for multi-dimensional arrays of unknown depth: When the number of levels in an array are unknown, recursion is a logical technique. The following code will process each subarray, removing zero-length values and any empty subarrays as it goes. Here is a demo of this code with a few sample inputs.

    $array=[
        ['Name'=>'','Array'=>['Keep'=>'Keep','Drop'=>['Drop2'=>'']],'EmailAddress'=>'','Pets'=>0,'Children'=>null],
        ['Name'=>'','EmailAddress'=>'','FavoriteNumber'=>'0']
    ];
    
    function removeEmptyValuesAndSubarrays($array){
       foreach($array as $k=>&$v){
            if(is_array($v)){
                $v=removeEmptyValuesAndSubarrays($v);  // filter subarray and update array
                if(!sizeof($v)){ // check array count
                    unset($array[$k]);
                }
            }elseif(!strlen($v)){  // this will handle (int) type values correctly
                unset($array[$k]);
            }
       }
       return $array;
    }
    
    var_export(removeEmptyValuesAndSubarrays($array));
    

    Output:

    array (
      0 => 
      array (
        'Array' => 
        array (
          'Keep' => 'Keep',
        ),
        'Pets' => 0,
      ),
      1 => 
      array (
        'FavoriteNumber' => '0',
      ),
    )
    

    If anyone discovers an input array that breaks my recursive method, please post it (in its simplest form) as a comment and I'll update my answer.

提交回复
热议问题