使用array_diff()时获取重复的值

时间:2013-05-27 05:12:17

标签: php duplicate-data array-difference

我有以下脚本:

// Query
$STH = $DB->prepare('SELECT * FROM players WHERE game = ?');
$STH->execute(array($_POST['game']));

// Get the stored photos
$Used = array();
while ($row = $STH->fetch())
  $Used[] = intval($row['photo']);

// (1)

// Get a random photo that is not stored already
$Photo = array_rand(array_diff(range(1, 6), $Used));

// (2)

// Insert the photo
$STH = $DB->prepare('INSERT INTO players (id, user, game, name, family, photo) VALUES (?, ?, ?, ?, ?, ?)');
$STH->execute(array($Id, $User->id, intval($_POST['game']), $Name, $Family, $Photo));

但是,这给了我数据库中的重复结果。具体来说,15重复多次(对于我执行的大约30个元素的测试而言,不是其他的,以强制6个元素范围。

此外,如果我在多次插入后在(1)中写var_dump(array_diff(range(1, 6), $Used));,它总是输出array(2) { [1]=> int(2) [5]=> int(6) }。所以,显然,数字2和6没有被考虑。如果我在(2)中echo $Photo;,则数字始终为15,因此显然不会出现插入问题。

那么,为什么数据库中的条目会重复?我的PHP代码出了什么问题?我肯定会在将来放置一个2字段唯一约束,但这不会修复保存随机照片ID的PHP。

1 个答案:

答案 0 :(得分:0)

愚蠢的我,我刚刚通过重读我认为我知道的东西来解决它:array_rand(当然)returns the KEY of the array。因此,它的工作方式如下:

// Query
$STH = $DB->prepare('SELECT * FROM players WHERE game = ?');
$STH->execute(array($_POST['game']));

// Get the stored photos
$Used = array();
while ($row = $STH->fetch())
  $Used[] = intval($row['photo']);

// Get a random photo that is not stored already
$Array = array_diff(range(1, 6), $Used);
$PhotoKey = array_rand($Array);
$Photo = $Array[$PhotoKey];

// Insert the photo
$STH = $DB->prepare('INSERT INTO players (id, user, game, name, family, photo) VALUES (?, ?, ?, ?, ?, ?)');
$STH->execute(array($Id, $User->id, intval($_POST['game']), $Name, $Family, $Photo));