2014-09-21 91 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