E. Edgo E. Edgo - 1 year ago 126
PHP Question

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

I have the following working code to output the states and output the relatd cities under each state. However, I want to shuffle or randomize the cities in each state. For example, if the State is California then I want to shuffle or randomize the relate outputted cities under it. I tried to use different methods for this such as ORDER BY RAND(), implode() and so on but didn't get the correct result.

$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>';

Any help on this matter would be greatly appreciated.

Answer Source
//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

    //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>';            
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download