【问题标题】:PHP unique numbers not uniquePHP唯一编号不是唯一的
【发布时间】:2015-05-01 19:42:20
【问题描述】:

我有两个不同的函数,一个从值 0-51(唯一)生成 5 张随机卡片,一个函数包含一个包含这 5 个卡片的数组,以及一个包含数组 #1 中的一些数字的数组将被存储。

函数二函数二是如果值不在数组#2 中,则将新值替换到数组#1。 这里似乎有什么问题。在生成了一些数字后,我得到了:

array(27,18,37,27,45) 

从 newCards 函数返回。

问题:我怎样才能修复 newCards 功能 100% 做它应该做的事? (又名使用第一个数组,检查数字是否在第二个数组中,如果不是,也在这里设置唯一)因为这里出了点问题,因为它返回了两个相同的数字。

代码:

    function UniqueCards() {
        $result = array();

        while(count($result) != 5) {
            $rand = rand(0,51); // reads as 0 = 1, and 51 = 52. aka starts at zero.

            if(!in_array($rand,$result)){
                $result[] = $rand;
            }
        }

        return $result;
    }

    function newCards($input,$exclude) {
            $i = 0;
            $output = array();
            while($i < count($input)) {
                $rand = rand(0,51);

                if(in_array($input[$i], $exclude)) {
                    $output[$i] = $input[$i];
                    $i++;
                }

                else if(!in_array($rand, $input)){
                    $output[$i] = $rand;
                    $i++;
                }
            }
            return $output;



    }

【问题讨论】:

标签: php arrays random


【解决方案1】:

如果您添加检查$rand 是否已经在$output 中,它会解决问题吗?

function newCards($input,$exclude) {
    ...
    else if(!in_array($rand, $input) && !in_array($rand, $output)) {
        $output[$i] = $rand;
        $i++;
    }
   ...
}

【讨论】:

  • 将检查并报告是否未修复。需要一些模拟才能看到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-05
  • 1970-01-01
  • 1970-01-01
  • 2014-01-28
  • 2011-05-21
相关资源
最近更新 更多