Search code examples
phparrayssorting

Sort a 2d array by a column ascending


What's the best way to sort this array alphabetically, by String1? The key numbering should always be numerical still.

Before:

Key     | String1    Int1 String2 Int2
--------------------------------------
0       | Alligator  3    Cake    7
1       | Crocodile  17   foobar  9
2       | Bear       1    test    6
3       | Aardvark   2    lolwhat 3

After:

Key     | String1    Int1 String2 Int2
--------------------------------------
0       | Aardvark   2    lolwhat 3
1       | Alligator  3    Cake    7
2       | Bear       1    test    6
3       | Crocodile  17   foobar  9     

Essentially, I have an array which has a bunch of arrays in it, how can I sort those arrays within the first array alphabetically using a particular element?


Solution

  • You probably want usort which lets you define a comparator callback function.

    http://www.php.net/manual/en/function.usort.php