简体   繁体   English

PHP:无法删除空数组

[英]PHP : cannot remove empty array

im trying to remove only the empty array我试图只删除空数组

Array
(
    [test1] =>  test1
    [test2] =>  test2
    [test3] =>  
)

i have tried the following:我尝试了以下方法:

$array = array_filter(array_map('array_filter', $array));

and

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 ] );
}

also i have tried to avoid adding any empty array:我也试图避免添加任何空数组:

foreach($attributes_array as $key => $single_attribute){
 if(!empty($attributes_array)){
  $attributes[$attributes_array[$key]['attribute_name']] = $attributes_array[$key] ['attribute_value'];     
 }
} 

any of the following code wont work in my case, any other possible soultion?以下任何代码在我的情况下都不起作用,还有其他可能的灵魂吗?

If your definition of empty is the same as empty() you can use array_filter without a callback:如果您对 empty 的定义与empty()相同,则可以使用array_filter而无需回调:

$array = array_filter($array);

Otherwise you can define a callback function to use with array_filter for your empty rules:否则,您可以定义一个回调array_filter与 array_filter 一起用于您的空规则:

$array = array_filter($array, function($val) {
    return $val !== '';
});

Demo: https://3v4l.org/lGhUC演示: https://3v4l.org/lGhUC

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM