从PHP数组中删除随机项

时间:2013-04-10 20:23:58

标签: php arrays

我需要将此数组的大小减小为X,所以我想删除X随机项。这是我的PHP数组:

Array
(
    [helping] => 3
    [me] => 2
    [stay] => 1
    [organized!] => 1
    [votre] => 4
    [passion,] => 1
    [action,] => 1
    [et] => 2
    [impact!] => 1
    [being] => 4



)

我尝试了array_rand()但它没有保留键/值。

5 个答案:

答案 0 :(得分:3)

array_rand()返回给定数组的随机键(或更多),使用它取消设置:

$randomKey = array_rand($array, 1);
unset($array[$randomKey]);

答案 1 :(得分:2)

array_rand()返回一个包含原始数组中键的数组。

您需要使用foreach循环从原始数组中删除密钥。

像这样:

// Suppose you need to delete 4 items.
$keys = array_rand($array, 4);

// Loop through the generated keys
foreach ($keys as $key) {
    unset($array[$key]);
}

答案 2 :(得分:0)

$foo = Array(
    "helping" => 3,
    "me" => 2,
    "stay" => 1,
    "organized!" => 1,
    "votre" => 4,
    "passion," => 1,
    "action," => 1,
    "et" => 2,
    "impact!" => 1,
    "being" => 4
);

$max = 5; //number of elements you wish to remain

for($i=0;$i<$max;$i++){ //looping through $max iterations, removing an element at random
     $rKey = array_rand($foo, 1);
     unset($foo[$rKey]);
}


die(print_r($foo));

答案 3 :(得分:0)

使用此,

$array = array(); // Your array

$max = 3;
$keys = array_rand($array, count($array) - $max);

// Loop through the generated keys
foreach ($keys as $key) {
    unset($array[$key]);
}

答案 4 :(得分:0)

如果您需要删除未知的商品编号,可以执行以下操作:

$myArr = [
    'helping' => 3,
    'me' => 2,
    'stay' => 1,
    'organized!' => 1,
    'votre' => 4,
    'passion,' => 1,
    'action,' => 1,
    'et' => 2,
    'impact!' => 1,
    'being' => 4,
];
$countToRemove = random_int(1, 2); // can return 1 or 2
$keysToRemove = array_rand($myArr, $countToRemove); // returns an int or array
// create the array to loop
foreach (\is_array($keysToRemove) ? $keysToRemove : [$keysToRemove] as $key) { 
    unset($myArr[$key]);
}
var_dump($myArr); die();

在这种情况下,它将从数组中随机删除1或2个项目。