sorting a multidimesional array
Posted: Tue Oct 12, 2010 8:16 am
Hi,
I want to sort on the population, but want to keep the values for each city next to each other
I want to sort on the population, but want to keep the values for each city next to each other
Code: Select all
<?php
$city = array("New York" => array("NY" => 8008278),
"Los Angeles" => array ("CA" => 369480),
"Chicago" => array ("IL" => 2896016),
"Houston" => array ("TX" => 1953631),
"Philadelphia" => array ("PA" => 1517550),
"Phoenix" => array ("AZ" => 1321045),
"San Diego" => array ("CA" => 1223400),
"Dallas" => array ("TX" => 1188580),
"San Antonio" => array ("TX" => 1144646),
"Detroit" => array ("MI" => 951270));
print ("<br>without sorting<br>");
//print array to screen
foreach ($city AS $name => $tags){
foreach ($tags as $states => $population) {
print "name: ".$name." tags: " .$states. " populatie: " .$population. "<br>";
}
}
print ("<br> sorting on the key value city<br>");
//sort on key value's of $city ($name)
ksort($city, SORT_ASC);
//printing the array to the screen
foreach ($city AS $name => $tags){
foreach ($tags as $states => $population) {
print "name: ".$name." tags: " .$states. " populatie: " .$population. "<br>";
}
}
print ("<br> sorting on the tags / population<br>");
// this is where it goes wrong I assume that $tags is the array wich it is, and the key value are the states names, but it doesn't work.
ksort($tags, SORT_ASC);
//printing the array to the screen
foreach ($city AS $name => $tags){
foreach ($tags as $states => $population) {
print "name: ".$name." tags: " .$states. " populatie: " .$population. "<br>";
}
}
?>