如何在php mysql

时间:2016-05-26 16:55:13

标签: php mysql random shuffle

我有以下工作代码输出状态并输出每个状态下的relatd城市。但是,我想对每个州的城市进行洗牌或随机化。例如,如果州是加利福尼亚州,那么我想要将其下的相关输出城市随机化或随机化。我尝试使用不同的方法,如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>';
     }

非常感谢任何有关此事的帮助。

2 个答案:

答案 0 :(得分:1)

//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>';            
    }
}

答案 1 :(得分:1)

更改您的查询添加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>';

}