Click to See Complete Forum and Search --> : Multidimension Array Sort


ripper2020
12-13-2006, 10:38 AM
Hello all I am pretty new to php and am working on a page with some order statistics. My current array has all the data I need and is as follows:
if($unique[$x] != NULL){
$db_loco[$x]['city']= $unique[$x];
$db_loco[$x]['orders'] = $orders;
$db_loco[$x]['state'] = $db_res[$x]['vSState'];}
}

So I end up with city state and number of orders all with the same index. The problem is the user needs to be able to sort this array by order number, city, or state. I have no clue how to do this or if it is even possible with this array, if there is a better way of making the array please let me know, I was looking into array_multisort but couldn't figure out how to do it. Any help would be much appreciated thanx.

NogDog
12-13-2006, 10:56 AM
You can use usort() (http://www.php.net/usort). For example, to sort by city:

function cmp($a, $b)
{
return strcmp($a["city"], $b["city"]);
}
usort($db_loco, "cmp");

ripper2020
12-13-2006, 11:56 AM
Thanx, could you explain a little bit about what this function does because I don't understand what its doing...for the most part it worked except the first 2 elements in the array are wrong...for example
IA Belle Plaine 1
NY springfield gardens 1
Other AGEGE ***** 1
MD ANNAPOLIS 1
After the first two it sppears they are in alphabetical order...if I knew more about what this function was doing i could try and fix...or do you know why it would be doing this?

NogDog
12-13-2006, 12:21 PM
Could be a couple things (at least 2 that occur to me, anyway): it could be an upper-/lower-case sorting problem, and there could be leading white-space throwing off the comparison. See if this is any better:

function cmp($a, $b)
{
return strcasecmp(trim($a["city"]), trim($b["city"]));
}
usort($db_loco, "cmp");

ShrineDesigns
12-13-2006, 12:22 PM
use strnatcmp() in place of strcmp()

NogDog
12-13-2006, 12:24 PM
use strnatcmp() in place of strcmp()
Or strnatcasecmp() (http://www.php.net/strnatcasecmp) :)

ripper2020
12-13-2006, 01:17 PM
the sorting for order totals works ascending( i think) that is it goes from least to greatest using the sort command...how do i make it do the opposite...greatest to least??

ShrineDesigns
12-13-2006, 01:45 PM
the reversal function for usort() is ursort()