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] 开发者_JAVA百科=> 1
)
php>
Anyways to do it not using loop?
I think that array_filter is what you need.
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
)
$a = array("a" => 1, "b" => 0, "c" => 1, "d" => 1, "e" => 0);
$b = array_filter($a);
You can use array_map
or array_filter
but I suggest you to stay with your code.
With PHP 5.3 you could use array_filter in combination with a closure:
$nonZeroes = array_filter($yourArray, function ($value) {
return $value;
});
精彩评论