For Laravel Collection:
$collection = collect([
['sn' => '2'],
['sn' => 'B'],
['sn' => '1'],
['sn' => '10'],
['sn' => 'A'],
['sn' => '13'],
]);
$sorted = $collection->sortBy('sn');
//print_r($collection);
Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[2] => Array
(
[sn] => 1
)
[0] => Array
(
[sn] => 2
)
[3] => Array
(
[sn] => 10
)
[5] => Array
(
[sn] => 13
)
[4] => Array
(
[sn] => A
)
[1] => Array
(
[sn] => B
)
)
)
As you can see, this will sort it correctly. However, if you want to sort it and reindex it then,
$sorted = $collection->sortBy('sn')->values()->all();
//print_r($sorted)
Array
(
[0] => Array
(
[sn] => 1
)
[1] => Array
(
[sn] => 2
)
[2] => Array
(
[sn] => 10
)
[3] => Array
(
[sn] => 13
)
[4] => Array
(
[sn] => A
)
[5] => Array
(
[sn] => B
)
)
Furthermore, You can also pass your own callback to determine how to sort the collection values.
$sorted = $collection->sortBy(function ($item, $key) {
//your logic
});
For more details: https://laravel.com/docs/5.8/collections#method-sortby