For eg.
I have the following array setup that has each major US city with its human population size.
$usapopstats = array(
array('New York',8008278),
array('Los Angeles',3694820),
array('Chicago',2896016),
array('Houston',1953631),
array('Philadelphia',1517550),
array('Phonenix',1321045),
array('San Diego',1223400),
array('Dallas',1188580),
array('San Antonio',1144646),
array('Detroit',951270)
);
I want to sort this information by the order of their population size. But when I tried using arsort function, it sorts array by the key data, rather than the value data ie sorted by city.
So my question is how do you programme the sorting by the population size for this type of multidimensional array? Any ideas?
If the array were rewritten like this
$usapopstats = array(
'New York'=>8008278,
'Los Angeles'=>3694820,
'Chicago'=>2896016,
'Houston'=>1953631,
'Philadelphia'=>1517550,
'Phoenix'=>1321045,
'San Diego'=>1223400,
'Dallas'=>1188580,
'San Antonio'=>1144646,
'Detroit'=>951270
);
asort($usapopstats);
This will sort the array by population size.
You need to create a user sort function (that is the most beautiful and fastest to program solution:
This is not the fastest code, fine for a list of say up to 1000 records, but I wouldn’t do it with an array with 100,000 entries. For each compare, the sort_helper function is being called, and since n log n compares are necessary, this means just as many function calls.
If you need this for a long list, encode the population in the key, and ksort: