簡體   English   中英

未按值設置關聯數組

[英]Unset associative array by value

我想按值刪除數組項。 無法指定密鑰。 這是數組。 我已按值(數值降序)對數組進行了排序。

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

如果要取消設置所有小於10的項目。我該如何做?

使用array_filter函數:

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

假設所有值都是整數:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM