0

嗨,我目前正在从数据库基本用户 ID 中查询比赛,但是我想避免在我的 results_array 中选择重复项,这个函数 getrandomspecies 接收一个 array_result,这个数组结果迭代 7 次。如何测试我没有在我的 results_array 中放置重复项?我得到了几个重复。

    function getrandomspecies($array_result){

     //database connection
     $dbn = adodbConnect();

     foreach($array_result as $possible){

    //query the results
    $querys= "select * from taxonomic_units where tsn = $possible";
    $resultss = $dbn -> Execute($querys);

    while($rowss=$resultss->FetchRow()){

        $id = $rowss['tsn']; //there ID
        $ranksss = $rowss['rank_id']; //ranking id, I choose 220 and 230



            if($ranksss == 220 || $ranksss == 230){
                $prelimary_array[] = $id;

            }
        }


   //grab random index
   $index = array_rand($prelimary_array,1);

   //put result id into a variable 
   $newspecies = $prelimary_array[$index];

   //put that variable in an array
    $results_array[] = $newspecies; //there is 7 newspecies/winners at the end, I dont want duplicates
 }

  return $results_array;
}
4

4 回答 4

0

循环您的结果数组,如果它不存在,则添加它。如果你最终得到少于 7 个,再做一次你的大循环。

替换这一行:

$results_array[] = $newspecies;

经过:

$loop_1_more_time=0;
if (isset($results_array)){
    foreach($results_array as $result){
        if ($result == $new_specie){
            $loop_1_more_time=1;
        }
    }
}
if ($loop_1_more_time == 0){
    $results_array[] = $newspecies;
}

//那里,如果 $loop_1_more_time 等于 1,则重新开始。要重新开始并确保您有 7 个而不是 6 个或更少,您可以用取决于 $array_result 的 count() 的“for”循环替换您的第一个“foreach”循环,并且 $array_result 将是 array_result [$i] 而不是 $possible。$i 将从 0 开始并在循环结束时递增。如果 $loop_1_more_time==1; 则不会增加。例子 :

for ($i = 0; $i < count($array_result); $i++) {
    //stuff
    //if ($loop_1_more_time=1;) { $i--; }
}
于 2013-08-06T18:27:45.883 回答
0

MySQL应该如下:

select distinct tsn, rank_id from taxonomic_units where tsn = $possible

但理想情况下,您应该使用准备好的语句。

于 2013-08-06T18:19:48.017 回答
0

那这个呢?您可以通过一个查询来做到这一点:

$querys= "select DISTINCT tsn from taxonomic_units where tsn IN (".implode(",",$array_result).") AND rank_id IN (220,230) ORDER BY RAND() LIMIT 7 ";
于 2013-08-06T18:21:16.030 回答
-1

为什么不尝试改组数组,然后选择前 X 个数字?

这样,不必检查结果数组是否有重复项,它一开始就不会出现

于 2013-08-06T18:14:12.013 回答