douaikuai2715 2015-06-22 20:11
浏览 58
已采纳

如何检查数据是否已存在,然后从数组中随机生成新数据

Okay so, I made an array containing 270+ different strings. The main goal is too echo out 60 strings from that array and combine them..

Ex. 1.String, 1.String2.

The 2 echo'd out strings are a combination, and should be together like 1-1 and 2-2, 3-3, and ect. In total there would be 30 combinations, but 60 strings.

Also, the way I have it is the first generated string should be combo'd with the 31st string generated

I was able to do this using a for loop, but now I had to use a mysql database to check if that combination already exists, then tell the random operator to generate another combination, until it finds a combination that doesn't already exist in the table. Here is what I have so far, but I'm not sure where to go from here.

$input = array("ITEM1", "ITEM2", "ITEM3", "ITEM4", "ITEM5"); //There are 273 items in the list
$rand_keys = array_rand($input, 60);
    $con = mysqli_connect($server, $user, $password, $name_db);
    for ($i = 0; $i <= 29; $i++) {

        $check = "SELECT * FROM contest WHERE name1 = '$input[$rand_keys[$i]]' AND name2 = '$input[$rand_keys[$i+30]]'";
        $rs = mysqli_query($con, $check);
        $data = mysqli_fetch_array($rs, MYSQLI_NUM);
        if ($data[$i] > 1) {

            //This combination already exists generate a new one until it generates one that doesn't exist
            while ($data[$i] > 1) {

                $rand_keys2 = array_rand($input, 2);
                $input[$rand_keys2[0]] = $input[$rand_keys[$i]];
                $input[$rand_keys2[1]] = $input[$rand_keys[$i + 30]];
            }
            echo $input[$rand_keys[$i]];
            echo '-';
            echo $input[$rand_keys[$i + 30]];
        } else {

            echo $input[$rand_keys[$i]];
            echo '-';
            echo $input[$rand_keys[$i + 30]];
        }
    }

That is all I have so far, I'm pretty sure my error is in the mysql statement could anyone fix that for me, and there is probably a bunch of mistakes in the rest of it. I'm just beginning, so don't mind some noob mistakes if you see them. Btw, when I run it, it just comes to a blank page.

  • 写回答

1条回答 默认 最新

  • doulan2827 2015-06-22 20:55
    关注

    In my personal opinion, NEVER try to get data from an array within quotes! Always do it outside of quotes; especially in multi-denominational arrays.

    '$input[$rand_keys[$i]]' should be rewritten as '".$input[$rand_keys[$i]]."' OR '{$input[$rand_keys[$i]]}'.

    In my opinion it is better to do it outside of quotes instead of using { }.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘