Lucky
Lucky

Reputation: 21

Sorting arrays in Laravel following a specific parametre

I have a variable which is an array of arrays

$janvier[]=array( 'type', 'date');

I want to sort it following the date so I used this code

$janvier=> $janvier->sortby($janvier['date'])

but it shows me this error:

call to a member function sortby() on array

Couldn't find what's wrong

I'm so used to low level languages this is my first time using a high level language

Upvotes: 2

Views: 110

Answers (2)

Piazzi
Piazzi

Reputation: 2636

sortBy is a collection method from laravel, you can't use it on a array.

If you want to sort the array by the key data use this code:


$janvier = array_multisort(array_values($janvier), SORT_DESC, array_keys($janvier), SORT_ASC, $janvier);

Look at the array_multisort method for more info

Upvotes: 1

Iftikhar uddin
Iftikhar uddin

Reputation: 3182

You can create a custom function for this case:

array_sort_by_column($array, 'date');

function array_sort_by_column(&$array, $column, $direction = SORT_ASC) {
    $reference_array = array();

    foreach($array as $key => $row) {
        $reference_array[$key] = $row[$column];
    }

    array_multisort($reference_array, $direction, $array);
}

For more you can check this question

Upvotes: 1

Related Questions