Adis Azhar
Adis Azhar

Reputation: 1022

Laravel sorting associative arrays

I am trying to sort an array based on a specific key but it's not working. The array is below when in JSON format. I want to sort it in ascending order by id_question.

This is what I have done so far:

public function compare($ar1, $ar2){
  if ($ar1['id_question']<$ar2['id_question']) {
    return 1;
  }else {
    return -1;
  }
}

Call the sort function:

uasort($related, Array ($this, 'compare'));

This is what it returns: enter image description here enter image description here

As you can see, it doesn't apply the sort.

It's done here is solution

usort($related, function($a, $b){
  if ($a['id_question'] < $b['id_question']) {
   return -1;
  }else {
   return 1;
  }
});

Upvotes: 0

Views: 2804

Answers (2)

Salvatore
Salvatore

Reputation: 1435

I hope this helps -

$listItem = collect($related)->sortBy('id_question')->toArray();

Upvotes: 6

Mahbub
Mahbub

Reputation: 4942

Please try:

$related = collect($related)->sortBy('id_question')->all();

Upvotes: 0

Related Questions