views:

222

answers:

2

I am new to PHP. I have a PHP array that is two dimensional. The "inner" array has a value that I want to sort on.

For example:

$myarray[1]['mycount']=12
$myarray[2]['mycount']=13
$myarray[3]['mycount']=9

I want to sort the "inner" array in descending order.

So the results for the following will be 13, 12, 9

foreach ($myarray as $myarr){
  print $myarr['mycount']
}

thanks in advance.

+4  A: 

You can use usort(); to sort by a user-defined comparison.

// Our own custom comparison function
function fixem($a, $b){
  if ($a["mycount"] == $b["mycount"]) { return 0; }
  return ($a["mycount"] < $b["mycount"]) ? -1 : 1;
}

// Our Data
$myarray[0]['mycount']=12
$myarray[1]['mycount']=13
$myarray[2]['mycount']=9

// Our Call to Sort the Data
usort($myArray, "fixem");

// Show new order
print "<pre>";
print_r($myArray);
print "</pre>";
Jonathan Sampson
I am getting the following error "sort() expects parameter 2 to be long, array given"
Tihom
I named the sort function sort which is already taken. I now changed it to cmp. I am getting a different error: usort() [function.usort]: Invalid comparison function
Tihom
Show me what your code looks like.
Jonathan Sampson
I found another post on stackoverflow. I needed to invoke array( $this, 'compare_label' ). Thanks everything works now!
Tihom
+3  A: 

Check array_multisort

hsz