如何循环遍历这个数组并删除所有空值:
[28] => Array
(
[Ivory] =>
[White] =>
)
[29] => Array
(
[Ivory] =>
[White] =>
)
[30] => Array
(
[Ivory] =>
[White] => 36
)
[31] => Array
(
[White] => 24
)
所以说它会从30中删除28,29和象牙…
谢谢!
我看到你已经有一个工作的解决方案,但只是为了好玩,与array_map的优点:
$array = array_filter(array_map('array_filter', $array));
我相信这将做你正在寻找的:
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 ] );
}
它将循环遍历你的外部数组,下降到它包含的任何数组,并删除值为空的键。然后,一旦完成,它将从外部数组中删除所有子值也为空的键。
注意,它不适用于泛型数组,只适用于您提供的(二维)数组。
另一种方法,使用preg_grep
:
foreach($array as $key => $subarray) {
$array[$key] = preg_grep('/^$/', $subarray, PREG_GREP_INVERT);
}
Update:忘记删除空数组了。@Ryan的回答中所展示的技巧也可以应用在这里。
对于任何正在寻找清洁变量的人来说,这是一个简单的数组或多维数组(深度未知的嵌套数组),这是我提出的解决方案:(它是作为类中的静态函数创建的,但也可以在类外工作->只需删除self::)
public static function clean($Array, $Strict=true)
{
if( ! is_array($Array))
{
return $Array;
}
$cleaned = array ();
foreach ($Array as $key => $value)
{
if($Strict)
{
if(!empty($value))
{
$tmp = self::clean($value,$Strict);
if(!empty($tmp))
{
$cleaned[$key] = $tmp;
}
}
}//strict
else
{
if(is_array($value))
{
if(!empty($value))
{
$tmp = self::clean($value,$Strict);
if(!empty($tmp))
{
$cleaned[$key] = $tmp;
}
}
}
elseif(strlen($value) > 0)
{
$tmp = self::clean($value,$Strict);
if(strlen($tmp) > 0)
{
$cleaned[$key] = $tmp;
}
}
}//not strict
} //end foreach
return $cleaned;
}
希望节省大家的时间:)干杯
您可能需要稍微编辑一下下面的代码。
foreach ($arr as $key => $value) {
if($value == "") {
unset($value[$key]);
}
}
//Check Array Remove Empty Key
$ixx=0; $ix=0;//Set Array First.
while(end(array_keys($a1))>=$ix){ //Check Last Key in Array
if($a1[$ix]!=""){ //Check Empty Key
$ax[$ixx]=$a1[$ix];$ixx++; } //Remove Empty Key
$ix++;
}
//End Check Array Remove Empty Key
print_r($ax);//Print Array After remove Empty Key