Array
(
[0] => 0 //value is int 0 which isn;t empty value
[1] => //this is empty value
[2] => //this is empty value
)
我想将上面的数组转换为以下形式,有谁能帮我吗?
非常感谢。
Array
(
[0] => 0
)
Array
(
[0] => 0 //value is int 0 which isn;t empty value
[1] => //this is empty value
[2] => //this is empty value
)
Array
(
[0] => 0
)
您可以使用array_filter函数来移除空值(null、false、''和0):
array_filter($array);
如果您不想从数组中删除0
,请参阅@Sabari的答案:
array_filter($array,'strlen');
您可以使用:
仅删除NULL值:
$new_array_without_nulls = array_filter($array_with_nulls, 'strlen');
删除假值:
$new_array_without_nulls = array_filter($array_with_nulls);
strlen
回调函数还会删除空字符串和 false
值(除了 null
)。 - Brad Kentarray_filter($array, function($var) {
//because you didn't define what is the empty value, I leave it to you
return !is_empty($var);
});
这是 array_filter
的典型应用案例。您首先需要定义一个函数,如果值应该被保留,则返回TRUE
,如果应该被删除,则返回FALSE
:
function preserve($value)
{
if ($value === 0) return TRUE;
return FALSE;
}
$array = array_filter($array, 'preserve');
然后在回调函数中(这里是preserve
),您指定什么是空的,什么不是。由于您在问题中没有明确说明,因此需要自行完成。
快速查找数字,包括零(0)
var_dump(
array_filter( array('0',0,1,2,3,'text') , 'is_numeric' )
);
/*
print :
array (size=5)
0 => string '0' (length=1)
1 => int 0
2 => int 1
3 => int 2
4 => int 3
*/
var_dump()
在数组上确定值的类型。 - BoltClock