Eduardo Santos Eduardo Santos - 1 month ago 13
PHP Question

Array shuffle repeating values

I have this code that make a query on a table and then do an insert in another insert a field with random integer value, but it is repeating when I have many records.

Code:

$d = connection::select(select * from tabela1);

foreach ($d as $reg) {

$c1 = $reg['c1'];
$c2 = $reg['c2'];
$c3 = $reg['c3'];

$count = count($reg);

$numbers = range(1, $count- 1);
srand((float) microtime() * 10000000);
shuffle($numbers);
foreach ($numbers as $number) {

}

connection::exec("insert into table2 (c1,c2,c3,seq)values('$c1','$c2','$c3',$number)");
}

Answer

You should create the array of random numbers outside the main foreach loop. Then just use one element of the array for each insert. This way you won't ever get any duplicates.

$d = connection::select("select * from tabela1");
$rows = $d->fetchAll();
$count = count($rows);
$numbers = range(1, $count);
srand((float) microtime() * 10000000);
shuffle($numbers);
foreach ($rows as $i => $reg) {
    $number = $numbers[$i];
    $c1 = $reg['c1'];
    $c2 = $reg['c2'];
    $c3 = $reg['c3'];
    connection::exec("insert into table2 (c1,c2,c3,seq)values('$c1','$c2','$c3',$number)");
}
Comments