0

我想按值删除数组项。无法指定密钥。这是数组。我已经按值对数组进行了排序,数字降序。

Array
(
    [this] => 15
    [that] => 10
    [other] => 9
    [random] => 8
    [keys] => 4
)

如果我想取消设置值小于 10 的所有项目。我该怎么做?

4

4 回答 4

4

使用array_filter功能:

$a = array_filter($a, function($x) { return !($x < 10); });
于 2012-09-20T19:08:44.650 回答
0
foreach($array as $key => $value)
  if( $value < 10 )
    unset($array[$key])
于 2012-09-20T19:08:54.567 回答
0

假设所有值都是整数:

for (i=9;i>=0;i--)
{
    while (array_search($i, $assocArray) !== false)
    {
        unset($assocArray[array_search($i, $assocArray)]);
    }
}

可能有更优雅的方法可以做到这一点,但发烧牢牢地控制着我的大脑:)

knittl 的回答是正确的,但是如果您使用的是旧版本的 PHP,则不能使用匿名函数,只需执行以下操作:

function filterFunc($v)
{
    return $v >= 10;
}
$yourArray = array_filter($yourArray,'filterFunc');

归功于 Knittl

于 2012-09-20T19:09:36.400 回答
0
$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 ) 
于 2012-09-20T19:12:06.863 回答