I have this sample array - as returned from a database query:
array (size=107)
0 =>
object(stdClass)[2310]
public 'country' => string 'Canada' (length=10)
public 'province' => string 'Ontario' (length=14)
public 'city' => string 'Toronto' (length=14)
public 'living_cost' => string 'high' (length=6)
1 =>
object(stdClass)[2311]
public 'country' => string 'Canada' (length=10)
public 'province' => string 'Ontario' (length=14)
public 'city' => string 'Barrie' (length=14)
public 'living_cost' => string 'low' (length=6)
2 =>
object(stdClass)[2311]
public 'country' => string 'Canada' (length=10)
public 'province' => string 'Nova Scotia' (length=14)
public 'city' => string 'Halifax' (length=14)
public 'living_cost' => string 'medium' (length=6)
3 =>
object(stdClass)[2312]
public 'country' => string 'USA' (length=10)
public 'province' => string 'California' (length=14)
public 'city' => string 'Los Angeles' (length=14)
public 'living_cost' => string 'high' (length=6)
4 =>
object(stdClass)[2313]
public 'country' => string 'USA' (length=10)
public 'province' => string 'Ohio' (length=14)
public 'city' => string 'Dayton' (length=14)
public 'living_cost' => string 'low' (length=6)
5 =>
object(stdClass)[2314]
public 'country' => string 'USA' (length=10)
public 'province' => string 'Illinois' (length=14)
public 'city' => string 'Chicago' (length=14)
public 'living_cost' => string 'high' (length=6)
6 =>
object(stdClass)[2315]
public 'country' => string 'USA' (length=10)
public 'province' => string 'Illinois' (length=14)
public 'city' => string 'Aurora' (length=14)
public 'living_cost' => string 'med' (length=6)
I'd like to get the unique Country values, so:
- Canada
- USA
And then for each, I'd like to list the province and cities, for example:
- Canada
- Ontario
- Toronto
- Barrie
- Ontario
USA
- California
- Los Angeles
- Illinois
- Chicago
- Aurora
I figured out how to get the unique countries, using:
$countries = array_unique(array_column($db_data, 'country'));
But not sure how to use the country array to now parse the database result to get the unique province and cities.
Please keep in mind, I'm not trying to get the unique values of each field - I need to first filter by the country so I can still relate the provinces and cities back to the country.
In other words: for each country, I want to retrieve a list of all provinces and all cities.
Any help is greatly appreciated!