0

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.

2
  • 3
    WARNING: When using mysqli you should be using parameterized queries and bind_param to add user data to your query. DO NOT use string interpolation or concatenation to accomplish this because you have created a severe SQL injection bug. NEVER put $_POST or $_GET data directly into a query, it can be very harmful if someone seeks to exploit your mistake. Commented May 26, 2016 at 17:00
  • Why by ORDER BY RAND() you couldn't get correct results? Commented May 27, 2016 at 4:58

2 Answers 2

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>';            
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Great answer, I tried your code and it works. However, I still have one issue which is when I add a different value to the city linking URL all the city URLs point to only one city. For example when I use the '.$city_with_dashes.' variable in this URL value then all output city links point to only one city: echo '<p style="margin-left: 10px;"><a href="examplesite.com/'.$city_with_dashes.'">'. $city .'</a></p>'; I have declared this variable in while loop as: $city_with_dashes = $row['city_name_with_dash']; I have included city_name_with_dash in MySQL SELECT statement as well.
In that case you have to add to city array not only name but also dashes. You can do it by array. I've updated my code in answer and there is now what you need (city name and city name with dash) :)
1

Change your query adding group_concat function and then take random value from arrays of cities

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

}

2 Comments

Thank you for your reply. I tried your code and it outputs only one random city per state. I am sorry if my original question was not that clear. I want to output all the related cities under states and shuffle or randomize them. For ex: if California has 25 cities, I want to list all of them under California and shuffle (randomize the cities not to have the same listing order) these cities every time when I refresh the page.
the code reques minimum changes because $city_names already contains list of all cities

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.