PHP阵列 - 删除空值 [英] PHP Array - Removing empty values

查看:112
本文介绍了PHP阵列 - 删除空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何遍历这个数组,并移除任何空值:

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

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

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

[30] => Array
    (
        [Ivory] => 
        [White] => 36
    )

[31] => Array
    (
        [White] => 24
    )

所以说,它会从30取出28,29,只是象牙...

So say it'd remove 28, 29 and just Ivory from 30...

谢谢!

推荐答案

我相信这会做你要找的内容:

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).

这篇关于PHP阵列 - 删除空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆