php> $a = array("a"=>1,"b"=>0,"c"=>1,"d"=>1,"e"=>0);
php> $b = array();
php> foreach ($a as $k =>$v){
... if($v != 0){
... $b["$k"] = $v;
... }
... }
php> print_r($b);
Array
(
[a] => 1
[c] => 1
[d] => 1
)
php>
无论如何不使用循环?
答案 0 :(得分:4)
我认为array_filter就是您所需要的。
function notZero($var)
{
// returns whether the input integer is not zero
return $var != 0;
}
$a = array("a"=>1,"b"=>0,"c"=>1,"d"=>1,"e"=>0);
print_r(array_filter($a, "notZero"));
//Prints what you need
Array
(
[a] => 1
[c] => 1
[d] => 1
)
答案 1 :(得分:2)
$a = array("a" => 1, "b" => 0, "c" => 1, "d" => 1, "e" => 0);
$b = array_filter($a);
答案 2 :(得分:1)
您可以使用array_map
或array_filter
,但我建议您继续使用您的代码。
答案 3 :(得分:1)
使用PHP 5.3,您可以将array_filter与闭包结合使用:
$nonZeroes = array_filter($yourArray, function ($value) {
return $value;
});