Home > Mobile >  Sort A Multi Dimensional Array In Laravel
Sort A Multi Dimensional Array In Laravel

Time:01-18

enter image description here

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?

CodePudding user response:

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
        )

)
  •  Tags:  
  • Related