array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pedroz
Forum Commoner
Posts: 99
Joined: Thu Nov 03, 2005 6:21 am

array

Post by pedroz »

$countries = array (
"london,united kingdom,",
"manchester,united kingdom",
"madrid,spain",
"lisbon,portugal"
);

With the array above, I would like to display the following

-united kingdom
london
manchester

-spain
madrid

-portugal
lisbon

thanks :)
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Re: array

Post by Kieran Huggins »

You'll need to generate a temp array like:

Code: Select all

$countries = Array(
  "United Kingdom" => Array(
    "Manchester",
    "London"
  ),
  // an so on
)
then iterate over that.
User avatar
Ambush Commander
DevNet Master
Posts: 3698
Joined: Mon Oct 25, 2004 9:29 pm
Location: New Jersey, US

Re: array

Post by Ambush Commander »

Code: Select all

$countries = array (
"london,united kingdom,",
"manchester,united kingdom",
"madrid,spain",
"lisbon,portugal"
);
$country_city = array();
 
foreach($countries as $city_string) {
  list($city, $country) = explode(',', $city_string,2);
  $country_city[$country][] = $city;
}
 
Displaying this is left as an exercise to the reader.
Post Reply