如何在 php mysql 中使用 array_rand() 或 shuffle() 函数

How to use array_rand() or shuffle() functions in php mysql

我有以下工作代码来输出状态并输出每个状态下的相关城市。但是,我想洗牌或随机化每个州的城市。例如,如果州是加利福尼亚州,那么我想洗牌或随机化其下的相关输出城市。我尝试为此使用不同的方法,例如 ORDER BY RAND()、implode() 等,但没有得到正确的结果。

    $get_result = "select DISTINCT state_name, city_name from country WHERE country_name='$select_country' ORDER BY state_name ASC";
    $result = array();
    $run = mysqli_query($dbconfig, $get_result);

    while ($row=mysqli_fetch_array($run)) {
        $state_name = $row['state_name'];
        $city_name = $row['city_name'];

        if (!isset($result[$state_name])) {
            echo '<p>' . $state_name . '</p>';
            $result[$state_name] = true;
        }

        echo '<p style="margin-left: 10px;"><a href="http://examplesite.com/'.$city_name.'">'. $city_name .'</a></p>';
     }

如有任何帮助,我们将不胜感激。

//first you need to fetch all data
$states = array();
while ($row=mysqli_fetch_array($run)){
    $state_name = $row['state_name'];
    $city_name = $row['city_name'];
    $city_with_dashes = $row['city_name_with_dash']; 
    if (!isset($states[$state_name])) {
        $states[$state_name] = array(
            'name' => $state_name,
            'cities' => array()
        );
    }
    //add city to state
    $states[$state_name]['cities'][] = array(
        'name' => $city_name,
        'dashes' => $city_with_dashes
    );
}

//now you can iterate by this data
foreach ($states as $state) {
    echo '<p>' . $state['name'] . '</p>';
    //shuffle state cities
    shuffle($state['cities']);

    //and display cities
    foreach ($state['cities'] as $city) {
        echo '<p style="margin-left: 10px;"><a href="http://examplesite.com/'.$city['dashes'].'">'. $city['name'] .'</a></p>';            
    }
}

更改您的查询,添加 group_concat 函数,然后从城市数组中获取随机值

$get_result = "select state_name, 
                      group_concat(city_name) city_name
                 from country 
                 WHERE country_name='$select_country' 
                 group by state_name 
                 ORDER BY state_name ASC";

$result = array();
$run = mysqli_query($dbconfig, $get_result);
while ($row=mysqli_fetch_array($run)){
    $state_name = $row['state_name'];
    $city_names = shuffle(explode(',', $row['city_name']));
    echo '<p>' . $state_name . '</p>';
    foreach ($city_names as $city)
        echo '<p style="margin-left: 10px;">
              <a href="http://examplesite.com/'.$city_name.'">'.
              $city_name[array_rand($city_name)] .'</a></p>';

}