随机选择数组中的元素,然后从数组中删除 [英] Randomly pick element in array then remove from the array

查看:161
本文介绍了随机选择数组中的元素,然后从数组中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多短语.我想循环地从数组中随机选择短语. 我不想在循环中再选择一次相同的短语. 我以为我可以随机选择该短语,然后在下一个循环之前将其删除.

I have an array of phrases. I'd like to randomly pick phrases from the array in a loop. I don't want to pick the same phrase more then once in the loop. I thought I could randomly pick the phrase and then delete it before the next loop.

http://codepad.org/11l0nStX

<?php
for ($i=0; $i<16; $i++) {
    $phrases = array(
        'Hello Sailor', 'Acid Test', 'Bear Garden', 'Botch A Job',
        'Dark Horse', 'In The Red', 'Man Up', 'Pan Out',
        'Quid Pro Quo', 'Rub It In', 'Turncoat', 'Yes Man',
        'All Wet', 'Bag Lady', 'Bean Feast', 'Big Wig',
    );

    $ran_Num = array_rand($phrases);
    $ran_Phrase = $phrases[$ran_Num];
    unset($phrases[$ran_Phrase]);
    echo $ran_Phrase . "\r\n";
    echo count($phrases) . "\r\n";
}

是否可以在每个循环中从数组中随机选择一个不同的短语?

Is it possible to randomly pick a different phrase from the array on each loop?

推荐答案

以随机顺序随机排列数组,然后弹出最后一个元素.

Shuffle the array in random order, and just pop the last element off.

$array = [...];

shuffle($array);

while($element = array_pop($array)){
  echo 'Random element:' . $element;
}

这篇关于随机选择数组中的元素,然后从数组中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆