6

hello friends I have an array that looks like this:

array:3 [▼
  0 => array:6 [▼
    "date" => "2016-05-31 15:08:33"
    0 => "31 May 16"
    1 => "aze"
    2 => "2"
    3 => "hi"
    4 => "487841464704194.jpg"
  ]
  1 => array:6 [▼
    "date" => "2016-05-31 15:26:09"
    0 => "31 May 16"
    1 => "aze"
    2 => "2"
    3 => "hey"
    4 => "487841464704194.jpg"
  ]
  2 => array:6 [▼
    "date" => "2016-06-01 11:33:06"
    0 => "01 Jun 16"
    1 => "aze"
    2 => "2"
    3 => "Dm me please"
    4 => "487841464704194.jpg"
  ]
]

My goal is to sort it by the date. So from new to old.

If tried this:

$comarrSorted = $comarr->sortByDesc('date');
dd($comarrSorted);

But I get this nasty error:

Call to a member function sortByDesc() on array

Anyone can help me out? I guess the error is caused because it's a collection function? Is it not possible to sort my array with this function?

Many Thanks in advance!

2

4 Answers 4

22

You can convert to a collection, call the sortBy() and the convert back to an array all on one line.

$sortedArr = collect($array)->sortBy('date')->all();
Sign up to request clarification or add additional context in comments.

1 Comment

This gives back a collection, for converting it back to an array, we can use the values() function. $sortedArr = collect($array)->sortBy('date')->values();
2

you have to create your own function

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);
}

3 Comments

There must be an easier way to do this with Laravel, or am I mistaken?
This is easier way, & I think, laravel not provide any array related function. If you get any better answer please let me know.
stackoverflow.com/a/52368760/10888237 This answer below is the better solution.
2

You can use usort() with custom comarison function.

function sortByDate($arr1, $arr2)
{
    $tmp1 = strtotime($arr1['date']);
    $tmp2 = strtotime($arr2['date']);
    return $tmp1 - $tmp2;
}
usort($array, 'date');

2 Comments

But I only have 1 array what do I ned $arr1 and $arr2 for?
I've added new answer.
2

You can use this solution to get the result:

collect($yourArray)->sortBy('Key')->values();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.