views:

95

answers:

3

Hello

I have tried adapting this code to use to sort a multidimensional array on a named key/field. The field is an integer what I need to sort smallest to biggest.

function myCmp($a, $b)
{
  return strcmp($a["days"], $b["days"]);
}

uasort($myArray, "myCmp");

This sorts the arrays as I need but in the wrong order. At the moment it sorts biggest to smallest, not using natural order. I need to sort smallest to biggest in natural order (eg 2 comes before 5, 12 and 24).

Any thoughts on achieving this?

+1  A: 

You can just reverse the parameters of strcmp :

function myCmp($a, $b)
{
  return strcmp($b["days"], $a["days"]);
}

uasort($myArray, "myCmp");
HoLyVieR
+1  A: 

Since you want to sort in natural order you should not be using strcmp, you can do:

function myCmp($a, $b)
{
  if ($a['days'] == $b['days']) return 0;
  return ($b['days'] > $a['days']) ? -1 : 1;
}

Here is a working example.

codaddict
If anyone is still watching, this does not return natural order. For the numbers 27, 2, 5 it returns 5, 27, 2
YsoL8
+2  A: 

strnatcmp() is your friend

e.g. (using a php 5.3 closure/anonymous function):

<?php
$myArray = array( 'foo'=>array('days'=>2), 'bar'=>array('days'=>22), 'ham'=>array('days'=>5), 'egg'=>array('days'=>12) );
uasort($myArray, function($a, $b) { return strnatcmp($a["days"], $b["days"]); });

foreach($myArray as $k=>$v) {
  echo $k, '=>', $v['days'], "\n";
}

prints

foo=>2
ham=>5
egg=>12
bar=>22
VolkerK