0

Hey guys i didn't found my answer in internet. Really simple question : How can i order an "complex" array in alphabetical order (the quicker way)

Exemple of an array :

array = [
    "0": [
             "username": "B_User1",
             "age": "134",
             "size": "4m13",
         ],
    "1": [
             "username": "A_User2",
             "age": "134",
             "size": "4m13",
         ],
    "2": [
             "username": "I_User3",
             "age": "134",
             "size": "4m13",
         ],
    "3": [
             "username": "R_User4",
             "age": "134",
             "size": "4m13",
         ],
    "4": [
             "username": "Z_User5",
             "age": "134",
             "size": "4m13",
         ],
    "6": [
             "username": "Q_User6",
             "age": "134",
             "size": "4m13",
         ],
];

And i want to sort this array in alphabetical order for username.

APoorDev
  • 131
  • 8
  • 3
    Possible duplicate: https://stackoverflow.com/questions/12865167/sort-multidimensional-array-by-second-level-key – David Dec 04 '18 at 11:18
  • 1
    Possible duplicate of [How can I sort arrays and data in PHP?](https://stackoverflow.com/questions/17364127/how-can-i-sort-arrays-and-data-in-php) – iainn Dec 04 '18 at 11:28

1 Answers1

3

use this function with PHP 5.3

usort($myArray, function($a, $b) {
    return $a['username'] - $b['username'];
});

or use array_multisort

 $keys = array_column($myArray, 'username');
 $result = array_multisort($keys, SORT_ASC, $myArray);

And, with PHP 7 you can use the spaceship operator:

usort($myArray, function($a, $b) {
    return $a['username'] <=> $b['username'];
});
Dave
  • 3,050
  • 6
  • 15
  • 28