-2

I used json_decode() to decode a JSON file into $data. So I think now I have an array of arrays:

$data:
1 first= "bob", last= "smith", middle= "t", ID= "123"
2 first= "paul", last= "adams", middle= "d", ID= "38"
3 first= "jon", last= "williams", middle= "g", ID= "132"

I want to sort $data by last. I think I need to use usort() but can't get it to work.

Chris
  • 93,263
  • 50
  • 204
  • 189

1 Answers1

1

Try this:

$data = [
    ['first' => 'bob', 'last' => 'smith', 'middle' => 't', 'ID' => '123'],
    ['first' => 'paul', 'last' => 'adams', 'middle' => 'd', 'ID' => '38'],
    ['first' => 'jon', 'last' => 'williams', 'middle' => 'g', 'ID' => '132'],
];

usort($data, function ($string1, $string2) {
    return strcmp($string1['last'], $string2['last']);
});

Output:

Array
(
    [0] => Array
        (
            [first] => paul
            [last] => adams
            [middle] => d
            [ID] => 38
        )

    [1] => Array
        (
            [first] => bob
            [last] => smith
            [middle] => t
            [ID] => 123
        )

    [2] => Array
        (
            [first] => jon
            [last] => williams
            [middle] => g
            [ID] => 132
        )

)
Lukas Hajdu
  • 786
  • 5
  • 18