2014-09-21 92 views
0

我需要從表格行中刪除重複項。 組合3個數字並生成所有可能的組合,以.html形式發佈 (如果所有數字都不相同,則爲6)數字必須各有6個數字,例如: 123,234等....減少數量的組合,如果一個數是相同的另一個 像112 我做了,到現在爲止... 孤立的數字,並將其存儲在一排:Concat獨特或刪除重複的字符串php/mysql

 $cc=GetRow("SELECT numbers FROM table"); 
     $n1=substr($cc, 0, 1); 
     $n2=substr($cc, 1, 1); 
     $n3=substr($cc, 2, 1); 

     //scrambling the numbers 
     $n1n2n3=$n1.$n2.$n3; //123 number stored 
     $n1n3n2=$n1.$n3.$n2; //132 number stored 
     $n2n1n3=$n2.$n1.$n3; //213 number stored 
     $n2n3n1=$n2.$n3.$n1; //231 number stored 
     $n3n1n2=$n3.$n1.$n2; //312 number stored 
     $n3n2n1=$n3.$n2.$n1; //321 number stored 

     $sql = sqlQuery("UPDATE table SET cc_concat = CONCAT_WS(',', '$n1n2n3', '$n1n3n2','$n2n1n3','$n2n3n1','$n3n1n2','$n3n2n1')"); 

     But here´s the problem: 
     if the number is 112 will generate duplicates, only 3 are uniques: 
     $n1n2n3=$n1.$n2.$n3; //112 number stored 
     $n1n3n2=$n1.$n3.$n2; //121 number stored 
     $n2n1n3=$n2.$n1.$n3; //112 number stored 
     $n2n3n1=$n2.$n3.$n1; //121 number stored 
     $n3n1n2=$n3.$n1.$n2; //211 number stored 
     $n3n2n1=$n3.$n2.$n1; //211 number stored 

     Is there a way to update the table without the duplicates? or remove the duplicates 
     after update? 

謝謝!

回答

0

你可以使用一個數組來存儲組合,並採取in_array()函數的優勢,以確保你不會有重複:

$combinations = array(); 
if (!in_array($n1n2n3, $combinations)) $combinations[] = $n1n2n3; 
if (!in_array($n1n3n2, $combinations)) $combinations[] = $n1n3n2; 
// Do the same for the rest 

// Then you could easily concatenate the result set from PHP. 
$cc_concat = implode(',', $combinations); 

// Finally update the database. 
$sql = sqlQuery("UPDATE table SET cc_concat = '{$cc_concat}' ");  

類似的東西應該解決的問題。

此外,您可能更願意使用算法從三位數組中爲您生成組合。對於這樣的算法,你可以檢查這個線程: Get all permutations of a PHP array?

+0

謝謝!奇蹟般有效!我現在會看到該算法。 Thx亞歷杭德羅! – nmj77 2014-09-21 19:49:12

+0

非常歡迎,我很高興! 我真的很感激+1;) 關心! – 2014-09-21 19:59:11

+0

我不允許...我的聲望很差:( – nmj77 2014-09-21 20:22:14