简体   繁体   English

未按值设置关联数组

[英]Unset associative array by value

I'd like to remove an array item by value. 我想按值删除数组项。 Key cannot be specified. 无法指定密钥。 Here is the array. 这是数组。 I have sorted the array by value, numeric descending. 我已按值(数值降序)对数组进行了排序。

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

If I want to unset all items that have a value less than 10. How do I do that? 如果要取消设置所有小于10的项目。我该如何做?

使用array_filter函数:

$a = array_filter($a, function($x) { return !($x < 10); });
foreach($array as $key => $value)
  if( $value < 10 )
    unset($array[$key])

Assuming that all values are ints: 假设所有值都是整数:

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

There probably are more elegant ways of doing this, but fever has a firm grip on my brain :) 可能有更优雅的方法,但是发烧使我的大脑牢牢地抓紧了:)

knittl's answer is correct, but if you're using an older version of PHP, you can' t use the anonymous function, just do: knittl的答案是正确的,但是如果您使用的是旧版本的PHP,则不能使用匿名函数,只需执行以下操作:

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

Credit to Knittl 归功于Knittl

$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 )

Run this code: 运行此代码:

foreach($test AS $key => $value) {
    if($value <= 10) {
        unset($test[$key]);
    }
}

Results are: 结果是:

echo "post: ";print_r($test);
post: Array ( [this] => 15 ) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM