从数据库表结果创建一个随机的 assoc 数组



我正在创建一个简单的拖放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
?>

通过在查询中使用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中修改西班牙语值。

最新更新