我有这个代码在表上进行查询,然后在另一个插入中插入一个具有随机整数值的字段,但是当我有很多记录时它会重复。
代码:
$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)");
}
答案 0 :(得分:0)
您应该在主foreach
循环之外创建随机数组。然后只为每个插入使用数组的一个元素。这样你就不会得到任何副本。
$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)");
}