Sorting countries from two tables by continent

Discussion in 'PHP' started by Cypherus, Jun 2, 2007.

  1. #1
    Hi there,

    I need help sorting out the countries after what continent their in. Here you can see the structure of the two tables. This is the query I'm currently using:

    
    SELECT rd_countries.name, rd_continents.name, rd_continents.id, rd_countries.id FROM rd_countries, rd_continents WHERE rd_countries.continent_id='2' ORDER BY rd_continents.id
    
    Code (markup):
    (Btw, you will see there is a "rd_" prefix added. Don't mind it!)

    So I know how to get the stuff out of a database. But I want to list them on my website after what continent the different countries belong to. How do I do this? I assume I have to put them all in one big array, but how?

       1.
          Array (
       2.
          [1] => Afrika
       3.
                  [1] => Name-of-country
       4.
                  [2] => Name-of-country
       5.
                  [3] => Name-of-country
       6.
          [2] => Asia
       7.
                  [1] => Name-of-country
       8.
                  [2] => Name-of-country
       9.
                  [3] => Name-of-country
      10.
          [3] => Europa
      11.
                  [1] => Name-of-country
      12.
                  [2] => Name-of-country
      13.
                  [3] => Name-of-country
      14.
          [4] => Nord-Amerika
      15.
                  [1] => Name-of-country
      16.
                  [2] => Name-of-country
      17.
                  [3] => Name-of-country
      18.
          [5] => Oseania
      19.
                  [1] => Name-of-country
      20.
                  [2] => Name-of-country
      21.
                  [3] => Name-of-country
      22.
          [6] => Sør-Amerika
      23.
          )
    PHP:
     
    Cypherus, Jun 2, 2007 IP
  2. krt

    krt Well-Known Member

    Messages:
    829
    Likes Received:
    38
    Best Answers:
    0
    Trophy Points:
    120
    #2
    Loop over the result set, and add to a countries array, e.g.:
    $countries = array();
    while ($row = mysql_fetch_array($res)) {
        $countries[$row['continent']][] = $row['country'];
    }
    PHP:
    Note that I would have my query written as follows:
    SELECT ctry.name country, cont.name continent, ctry.id, cont.id FROM rd_countries ctry, rd_continents cont ORDER BY rd_continents.id
    Code (markup):
     
    krt, Jun 2, 2007 IP
    Cypherus likes this.
  3. Cypherus

    Cypherus Peon

    Messages:
    1,551
    Likes Received:
    102
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thank you :)
     
    Cypherus, Jun 2, 2007 IP