Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Sorting a multi-dimensional array by field name

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).

like image 470
YsoL8 Avatar asked Dec 07 '25 09:12

YsoL8


1 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
like image 177
VolkerK Avatar answered Dec 08 '25 23:12

VolkerK