我想按值删除数组项。密钥不能被指定。这是数组。我已经按数值降序排列了数组。按值取消设置关联数组
Array
(
[this] => 15
[that] => 10
[other] => 9
[random] => 8
[keys] => 4
)
如果我想取消设置的值小于10的所有项目。我该怎么做?
我想按值删除数组项。密钥不能被指定。这是数组。我已经按数值降序排列了数组。按值取消设置关联数组
Array
(
[this] => 15
[that] => 10
[other] => 9
[random] => 8
[keys] => 4
)
如果我想取消设置的值小于10的所有项目。我该怎么做?
$test = array(
"this" => 15,
"that" => 10,
"other" => 9,
"random" => 8,
"keys" => 4
);
echo "pre: ";print_r($test);
pre: Array ([this] => 15 [that] => 10 [other] => 9 [random] => 8 [keys] => 4)
运行这段代码:
foreach($test AS $key => $value) {
if($value <= 10) {
unset($test[$key]);
}
}
结果是:
echo "post: ";print_r($test);
post: Array ([this] => 15)
使用array_filter
功能:
$a = array_filter($a, function($x) { return !($x < 10); });
foreach($array as $key => $value)
if($value < 10)
unset($array[$key])
如何引用一个值会产生任何影响的值? –
你是对的,必须有一个脑筋 – JvdBerg
假定所有的值是整型:
for (i=9;i>=0;i--)
{
while (array_search($i, $assocArray) !== false)
{
unset($assocArray[array_search($i, $assocArray)]);
}
}
有可能这样做的更优雅的方式,但发烧上有一个坚定的抓地力我的大脑:)
knittl的答案是正确的,但如果您使用的是旧版本的PHP ,你可以” T使用匿名函数,只是做:
function filterFunc($v)
{
return $v >= 10;
}
$yourArray = array_filter($yourArray,'filterFunc');
感谢Knittl
http://php.net/manual/en/function.array-filter.php –
这只是一维数组。 – knittl