2013-08-06 37 views
0

您好,我目前正在查詢從數據庫基礎用戶ID比賽,但是我想避免在我的results_array中選擇重複,這個函數getrandomspecies接收array_result,這個數組結果迭代7次。如何測試我不把重複項放在我的results_array中?我得到了幾個重複。Php如何檢查重複結果?

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; 
} 
+0

現在有簡單的方法來解決這個問題。你可以嘗試在你的查詢中使用group by *從taxonomic_units中選擇*其中tsn = $可能的組由tsn。或由其他一些庫侖組合。 – pregmatch

+0

改變你的mysql查詢來選擇不同或分組由 –

+0

使用Mysql的'DISTINCT' –

回答

-1

爲什麼不嘗試洗牌數組,然後選擇第一個X數?

通過這種方式,而不必重複檢查結果陣,就再也回不來了擺在首位

+0

儘管可能有10個重複,這可能在洗牌後結束在數組頂部 –

+0

不應該,這應該在sql語句中完成 – sgroves

0

MySQL的應該是以下幾點:

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

但你應該理想地使用準備好的聲明。

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 "; 
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]而不是$可能。 $我會從0開始,並在循環的每一端增加。如果$ loop_1_more_time == 1;它不會增加。 例如:

for ($i = 0; $i < count($array_result); $i++) { 
    //stuff 
    //if ($loop_1_more_time=1;) { $i--; } 
} 
+0

嘿,我得到了一個無限循環,我嘗試了你的解決方案,你能幫我嗎?我逐字執行它 – user2604754

+0

*請注意,您在開始時計算的數組必須是非關聯的。你可以報告的事實是,即使它重新啓動,每個循環中也不會有7個可能的不同元素,因此循環變得無限並且永遠搜索新的元素,而沒有。 –

+0

我還在兩個代碼示例中添加了更正 –