简体   繁体   中英

Grouping unique values from an SQL column as headings, another column as subheadings and another as sub-subheadings Using PHP

I have a table with columns and values similar to:

|country  |region  |city       |
|------------------------------|
|USA      |Maine   |Bar Harbor |
|Australia|Victoria|Melbourne  |
|Spain    |Valencia|Enguera    |
|Australia|Victoria|Colbo      |
|USA      |New York|NYC        |

I'd like to display this in alphabetical order like this:

Australia
 Victoria
  Colbo
  Melbourne

Spain
 Valencia
  Enguera

USA
 Maine
  Bar Harbor
 New York
  NYC

I have attempted to use nested for loops which I found suggested in this question: How do I get unique values from a column and group them with values from another column? But I've had difficulty adding the third value column.

  • Select from the given table order by country, region, city.
  • Loop through the result set and print the fields. (with the exceptions I describe below.) (X)
  • After each iteration save the last record
    • (X) print only the country if it doesn't equal with the previous
    • (X) and print only the region if the country/region doesn't equal with the previous.

(when you skip a printing, you can print a few spaces, to create a tabulated like view like in your example.)

hopefully work

    select country,region,city from table group by country,region 
order by country asc,region desc ,city desc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM