Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

4 Answers

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
share|improve this answer

You can just reverse the parameters of strcmp :

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

uasort($myArray, "myCmp");
share|improve this answer

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.

share|improve this answer
If anyone is still watching, this does not return natural order. For the numbers 27, 2, 5 it returns 5, 27, 2 – YsoL8 Sep 13 '10 at 9:48

Try using array_multisort for sorting multi-dimensional array. It's simple and easy.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.