【问题标题】:I need to select two words without repeat them (PHP)我需要选择两个单词而不重复(PHP)
【发布时间】:2015-06-22 03:21:36
【问题描述】:

我有一个数组列表,我想从这个列表中选择两个单词而不重复它们。但是我尝试了很多东西,但没有任何效果。有当前代码:

$randomq2[] = "one";
$randomq2[] = "two";
$randomq2[] = "three";


srand ((double) microtime() * 1000000);
$getrando1 = rand(0,count($randomq2)-1);
$getrando2 = rand(0,count($randomq2)-1);


$wordone = $getrando1[$conco1];
$wordtwo = $getrando2[$conco2];

【问题讨论】:

  • 仅供参考:您可以接受如何最大程度地帮助您并解决您的问题的答案 (meta.stackexchange.com/q/5234)!
  • 您遇到什么错误?真正的问题是什么?

标签: php arrays select


【解决方案1】:

我不太明白你的问题

但是试试这个

<?php
$a=array("a"=>"red","b"=>"green","c"=>"red");
print_r(array_unique($a));
?>

这将删除数组中的重复值

【讨论】:

    【解决方案2】:

    这应该适合你:

    (这里我首先从$randomq2array_unique() 获取所有唯一元素。然后我只是shuffle() 数组,最后我只是从array_slice() 开头提取2 个元素)

    <?php
    
        $randomq2 = array_unique($randomq2);
        shuffle($randomq2);
        $random = array_slice($randomq2, 0, 2);
    
        print_r($random);
    
    ?>
    

    【讨论】:

    • 工作过,谢谢你解释它是如何工作的:P
    • 我相信他只需要shuffle,因为他写的代码有问题可以两次得到相同的array key,用shuffle这不是问题。
    【解决方案3】:

    你可以通过以下方式:

    $getrando1 = rand(0,count($randomq2)-1);
    $getrando2 = rand(0,count($randomq2)-1);
    while ($getrando2 == $getrando1)
        $getrando2 = rand(0,count($randomq2)-1);
    

    另外 - 我建议你使用 mt_rand 而不是简单的 rand

    【讨论】:

    • 谢谢,成功了! :D(我在 lmao 之前尝试过 If 现在我明白了)
    猜你喜欢
    • 1970-01-01
    • 2013-10-30
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多