让PHP shuffle输出结果的问题

时间:2015-07-16 13:37:40

标签: php foreach while-loop shuffle

我正在尝试将我在数据库中的用户随机播放,然后输出这些结果的名字和姓氏。我在这个文件中有PHP错误编码,并没有抛出任何错误。什么都没有输出甚至..

if ($shuffle_firstname == true) { echo $shuffle_firstname . $shuffle_lastname; } else { echo "No users have been registered yet."; }

有谁看到我做错了什么?

$con = mysqli_connect("localhost", "root", "", "db");
$shuffle_run = mysqli_query($con,"SELECT * FROM users WHERE `group`= 3");
$shuffle_numrows = mysqli_num_rows($shuffle_run);
if( $shuffle_numrows > 0) {
    while($shuffle_row = mysqli_fetch_assoc($shuffle_run)){
        $shuffle_id = $shuffle_row['id'];
        $shuffle_firstname = $suffle_row['firstname'];
        $shuffle_lastname = $shuffle_row['lastname'];
        $shuffle_username = $shuffle_row['username'];
        $shuffle_email = $shuffle_row['email'];

        if ($shuffle_firstname == true) {
            echo $shuffle_firstname . $shuffle_lastname;
        } else {
            echo "No users have been registered yet.";
        }
    }
}

if(isset($_POST['shuffle']))  {
    $shuffle_row = array();
    shuffle($shuffle_row);
    foreach ($shuffle_row as $shuffle) {
        echo $shuffle_firstname . " " . $shuffle_lastname;
    }
}

?>
<input type="submit" value="Shuffle" name="shuffle">

1 个答案:

答案 0 :(得分:1)

您使用空数组覆盖结果,然后在空数组上使用shuffle,然后使用foreach循环空数组。我已经清理了代码,你能尝试一下吗?

<?php
$con = mysqli_connect("localhost", "root", "", "db");
$query = mysqli_query($con, "SELECT * FROM users WHERE `group` = 3");

echo 'Normal results: <br>';
$array = array();
while ($row = mysqli_fetch_assoc($query)) {
    $array[] = $row;
    echo $row['firstname'] . ' ' . $row['lastname'] . '<br>';
}
if (isset($_POST['shuffle'])) {
    shuffle($array);
    echo 'Shuffled results: <br>';
    foreach ($array as $result) {
        echo $result['firstname'] . ' ' . $result['lastname'] . '<br>';
    }
    // echo $results[0]['firstname'] . ' ' . $results[0]['lastname']; // To display one random result
}
?>
<form method="post">
    <input type="submit" value="Shuffle" name="shuffle">
</form>