从数据库表结果创建随机关联数组

时间:2017-04-15 20:30:44

标签: php loops select random mysqli

我正在创建一个简单的拖放jquery游戏,它需要从我的数据库表中删除10行的结果集。我可以通过重复10个单独的查询块来实现这一点,但我确信必须有一个更优雅的方法来执行此操作。我尝试了许多东西,包括循环和追加等等,但我无法使循环方式正常工作。

我无法使这个循环版本起作用:

<script type="text/javascript">
<?php
// first create list of 10 fake id's and shuffle them
$id_array = range(0, 9);
shuffle($id_array);

/*
    // then loop to fetch all data from MySql table with spanish, english
    // CANNOT GET THIS WORKiNG ?
    for (i = 0; i < 10; i++) {
        $query = "SELECT id, english, spanish FROM colors WHERE id = $id_array[i]";
        $result = mysqli_query($link, $query);
        $row = mysqli_fetch_array($result);
        $rand_value.append(i) = $row['english'];
        $name.append(i) = strtoupper($row['spanish']);
    }
*/

写出来有效,但必须有一个更简单的方法......

<script type="text/javascript">
<?php
// create all input from MySql table for drag and drop area with spanish, english
$query = "SELECT id, english, spanish FROM colors WHERE id = $id_array[0]";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$random_key0 = $row['id'];
$rand_value0 = $row['english'];
$name0 = strtoupper($row['spanish']);

$query = "SELECT id, english, spanish FROM colors WHERE id = $id_array[1]";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$random_key1 = $row['id'];
$rand_value1 = $row['english'];
$name1 = strtoupper($row['spanish']);  

// and so on to run 10 queries total
?>

1 个答案:

答案 0 :(得分:0)

在查询中使用RAND()简化所有内容。只使用一个查询并以随机顺序检索所有十行。

$query="SELECT id,english,UPPER(spanish) FROM colors ORDER BY RAND() LIMIT 10;";
$result=mysqli_query($link,$query);
while($row=mysqli_fetch_array($result)){
    // prepare and handle your results using: $row['id'], $row['english'], $row['spanish']
}

编辑:我已将UPPER()添加到查询中,以便稍后您的php中不需要修改西班牙语值。