Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort a multi-dimensional associative array?

Okay, I have an array that is used to transport names, it looks like this:

array(2) {
  [0]=>
  array(3) {
    ["firstName"]=>
    string(3) "Joe"
    ["lastName"]=>
    string(5) "Black"
    ["uid"]=>
    int(3225)
  }
  [1]=>
  array(3) {
    ["firstName"]=>
    string(4) "John"
    ["lastName"]=>
    string(3) "Doe"
    ["uid"]=>
    int(3516)
  }
}

Now, how do I sort this array by lastName?

like image 535
nkcmr Avatar asked Nov 02 '11 16:11

nkcmr


1 Answers

StackOverflow has lots of similar questions, but let me give you a quick example. For this, you can use the usort() function.

PHP 5.3 example (not the nicest one, but might be easier to understand):

uasort($array, function ($i, $j) {
    $a = $i['lastName'];
    $b = $j['lastName'];
    if ($a == $b) return 0;
    elseif ($a > $b) return 1;
    else return -1;
});
like image 140
kapa Avatar answered Oct 10 '22 03:10

kapa