从数组 PHP 中过滤掉负整数
Filter out negative integers from an array PHP
我正在尝试从以下数组中删除所有负整数:
$array = array([-122,121,-124,124,-121,122,-122,124,-121,124,-122,125,-121,121,-123,122,-124,120]);
我已经尝试了以下方法,但它不起作用,因为我真的不明白 array_filter
是如何工作的:
function positive($var) {
if ($var >= 0) {
return $var;
}
}
print_r(array_filter($array, positive($var)));
如何将每个值发送到 positive
函数?或者有更好的方法吗? array_walk
或 array_map
也许?
array array_filter ( array $array [, callable $callback [, int $flag =
0 ]] )
Iterates over each value in the array passing them to the callback
function. If the callback function returns true, the current value
from array is returned into the result array. Array keys are
preserved.
使用测试正值的回调:
$array = [-122,121,-124,124,-121,122,-122,124,-121,124,-122,125,-121,121,-123,122,-124,120];
$positive_integers = array_filter($array, function($value) {
return $value > 0;
});
使用此代码:
<?php
$array = array([-122,121,-124,124,-121,122,-122,124,-121,124,-122,125,-121,121,-123,122,-124,120]);
function positive($var)
{
if ($var >= 0)
{
return true;
}
}
print_r(array_filter($array[0], 'positive'));
您必须将 $array[0]
作为参数传递才能修改数组。您已在第一个元素 array([-122,...,-124,120]);
中声明了数组,因此要过滤数组,您需要传递 $array[0]
.
输出为:
Array ( [1] => 121 [3] => 124 [5] => 122 [7] => 124 [9] => 124 [11] => 125 [13] => 121 [15] => 122 [17] => 120 )
我正在尝试从以下数组中删除所有负整数:
$array = array([-122,121,-124,124,-121,122,-122,124,-121,124,-122,125,-121,121,-123,122,-124,120]);
我已经尝试了以下方法,但它不起作用,因为我真的不明白 array_filter
是如何工作的:
function positive($var) {
if ($var >= 0) {
return $var;
}
}
print_r(array_filter($array, positive($var)));
如何将每个值发送到 positive
函数?或者有更好的方法吗? array_walk
或 array_map
也许?
array array_filter ( array $array [, callable $callback [, int $flag = 0 ]] )
Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. Array keys are preserved.
使用测试正值的回调:
$array = [-122,121,-124,124,-121,122,-122,124,-121,124,-122,125,-121,121,-123,122,-124,120];
$positive_integers = array_filter($array, function($value) {
return $value > 0;
});
使用此代码:
<?php
$array = array([-122,121,-124,124,-121,122,-122,124,-121,124,-122,125,-121,121,-123,122,-124,120]);
function positive($var)
{
if ($var >= 0)
{
return true;
}
}
print_r(array_filter($array[0], 'positive'));
您必须将 $array[0]
作为参数传递才能修改数组。您已在第一个元素 array([-122,...,-124,120]);
中声明了数组,因此要过滤数组,您需要传递 $array[0]
.
输出为:
Array ( [1] => 121 [3] => 124 [5] => 122 [7] => 124 [9] => 124 [11] => 125 [13] => 121 [15] => 122 [17] => 120 )