PHP Array - Removing empty values

前端 未结 6 1763
别跟我提以往
别跟我提以往 2020-12-28 21:43

How do I loop through this array and remove any empty values:

[28] => Array
    (
        [Ivory] => 
        [White] => 
    )

[29] => Array
           


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-28 21:43

    I believe this will do what you're looking for:

    foreach( $array as $key => $value ) {
        if( is_array( $value ) ) {
            foreach( $value as $key2 => $value2 ) {
                if( empty( $value2 ) ) 
                    unset( $array[ $key ][ $key2 ] );
            }
        }
        if( empty( $array[ $key ] ) )
            unset( $array[ $key ] );
    }
    

    It will loop through your outer array, descend into any arrays it contains and remove keys whose values are empty. Then, once it's done that, it will remove any keys from the outer array whose subvalues were all empty, too.

    Note that it wouldn't work for a generic array, just the one you've provided (two-dimensional).

提交回复
热议问题