2014-09-28 55 views
0

除以记录我要生成的代码的所有组合对于阵列建议生成并在MySQL

"2", "3", "4", "6", "7", "8", "9", "Q", "W", "R", "T", "Y", "P", "D", "F", "G", "H", "J", "K", "X", "C", "V", "B", "M" 

有效码必须具有25个simbols,并有5个段分离由“ - ”

例如

34267-89QWR-TYPDF-GHJKX-CVBMG

43267-89QWR-TYPDF-GHJKX-CVBMG

生成每个组合脚本后必须插入表代码。我尝试使用它,但它只生成该数组的所有组合,但不包含25个符号的代码。请帮我

<?php 

require 'config.php'; 

function pc_permute($items, $perms = array()) { 
    if (empty($items)) { 
     $result = join('', $perms); 

     mysql_query("INSERT INTO gen (code) VALUES ('$result');") or die ('Wystąpił błąd w zapytaniu lub kod nie zostal dodany.'); 

    } else { 
     for ($i = count($items) - 1; $i >= 0; --$i) { 
      $newitems = $items; 
      $newperms = $perms; 
      list($foo) = array_splice($newitems, $i, 1); 
      array_unshift($newperms, $foo); 
      pc_permute($newitems, $newperms); 
     } 
    } 
} 

$arr = array("2", "3", "4", "6", "7", "8", "9", "Q", "W", "R", "T", "Y", "P", "D", "F", "G", "H", "J", "K", "X", "C", "V", "B", "M"); 

pc_permute($arr); 

?> 

如果你能帮助我,我会非常高兴。

PS。请添加语句在一个监视模式不可能是5个相同simbols

例如:

AAAAB-AAAAB-AAAAB-AAAAB-AAAAB 很好的结合

AAAAA-AAAAA-AAAAA-AAAAA- AAAAA 糟糕的组合

AAAAA-AAAAB-AAAAB-AAAAB-AAAAB 糟糕的组合

回答

3
function generateId($arr, $max) { //$max sets the amount of characters you want it to be 
    $results = ''; 
    for($i = 0;$i < $max;$i++) { 
     if($i % 5 == 0 && $i > 0) { //appends '-' every 5 characters 
      $results .= '-'; 
     } 
     $rand = rand(0, (count($arr) - 1)); 
     $results .= $arr[$rand]; 
    } 
    if(preg_match('/(.)\\1{4}/', $results)) return generateId($arr, $max); //checks if 5 characters repeat 
    else return $results; 
} 

$id = generateId($arr, 25); //pass your array of characters as argument 
+0

Thaks回复,但我有一个建议。你可以添加验证是代码包括25个符号或29个符号与分隔符?在一些测试中,你的脚本给了我一段代码4个符号。例如: 3WXQG-3H6Q-M9BYQ-G7HJW-2Y92B – user3399458 2014-09-28 16:51:50

+0

'count($ arr)'需要'count($ arr)-1'在'$ rand = rand(0,count($ arr)); ' - >'$ rand = rand(0,count($ arr)-1);'。 – Sean 2014-09-28 16:52:08

+0

是的,我刚刚意识到这一点,并改变了它 – 2014-09-28 16:55:06