This is the result of dd() that I use in my controller on laravel 8. I want to sort the data based on the JB column. I can't use the manual order by in SQL syntax because I get JB from complex DB RAW. Therefore I want to sort this multi-dimensional array using php. Does anyone know how to sort the multi-dimensional array based on JB column value?
Asked
Active
Viewed 629 times
2 Answers
2
here I go...
you can use array_multisort
PHP function. Link
$new = [
[
'id' => 13,
'name' => 'Tony',
'jb' => 3,
],
[
'id' => 15,
'name' => 'Joe',
'jb' => 2,
],
[
'id' => 16,
'name' => 'Ross',
'jb' => 1,
],
[
'id' => 18,
'name' => 'Monika',
'jb' => 5,
],
[
'id' => 20,
'name' => 'Joye',
'jb' => 7,
],
];
$keys = array_column($new, 'jb');
array_multisort($keys, SORT_ASC, $new);
so as a result you will get link,
Array
(
[0] => Array
(
[id] => 16
[name] => Ross
[jb] => 1
)
[1] => Array
(
[id] => 15
[name] => Joe
[jb] => 2
)
[2] => Array
(
[id] => 13
[name] => Tony
[jb] => 3
)
[3] => Array
(
[id] => 18
[name] => Monika
[jb] => 5
)
[4] => Array
(
[id] => 20
[name] => Joye
[jb] => 7
)
)

Mitesh Rathod
- 879
- 5
- 18
0
sortBy method solves your issue. Laravel really has a strong bunch of methods in collections. Below code block shows an example.
$collection = collect([
['name' => 'Desk', 'price' => 200],
['name' => 'Chair', 'price' => 100],
['name' => 'Bookcase', 'price' => 150],
]);
$sorted = $collection->sortBy('price');
$sorted->values()->all();
/*
[
['name' => 'Chair', 'price' => 100],
['name' => 'Bookcase', 'price' => 150],
['name' => 'Desk', 'price' => 200],
]
*/

Sevan
- 669
- 1
- 5
- 18