我想从数组中删除空值和空值$listValues
。在这里,我使用 array_filter
删除了空值。示例代码:
$listValues = array("one", "two", "null","three","","four","null");
$resultValues = array_filter($listValues);
echo "<pre>";
print_r($resultValues);
echo "</pre>";
结果:
Array ( [0] => one [1] => two [2] => null [3] => three [5] => four [6] => null )
但我想
Array ( [0] => one [1] => two [3] => three [5] => four )
任何建议都非常感谢。
试试这个: 使用 array_diff() 函数比较两个(或多个)数组的值,并返回差异。 以删除 null 和 " 。如果您需要删除更多字段,请在数组中添加该值
<?php
$listValues = array("one", "two", "null","three","","four","null");
echo "<pre>";
$a=array_values(array_diff($listValues,array("null","")));
print_r($a);
echo "</pre>";
?>
输出:
Array
(
[0] => one
[1] => two
[2] => three
[3] => four
)
指http://www.w3schools.com/php/func_array_diff.asp
尝试使用第二个参数作为用户定义的函数array_filter,如下所示:
$listValues = array("one", "two", "null","three","","four","null");
print_r(array_filter($listValues, "filter"));
function filter($elmnt) {
if ($elmnt != "null" && $elmnt != "" ) {
return $elmnt;
}
}
使用以下代码,首先我更正了一个数组的索引,然后从数组中取消设置空值,然后再次更正数组索引:
$listValues = array("one", "two", "null","three","","four","null");
$listValues = array_values($listValues);
$temp = $listValues;
for($loop=0; $loop<count($listValues); $loop++){
if($listValues[$loop] == "" || $listValues[$loop] == "null"){
unset($temp[$loop]);
}
}
$listValues = $temp;
$listValues = array_values($listValues);
echo "<pre>";
print_r($listValues);
echo "</pre>"; die;
但是,如果您希望相同的索引获得此输出:
Array ( [0] => one [1] => two [3] => three [5] => four )
那么在<pre>
之前不要使用它:
$listValues = array_values($listValues);