0

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;
  }
});
3
  • Don't post images of text. Commented Jul 1, 2018 at 19:02
  • Sorry Andreas!! Commented Jul 1, 2018 at 19:03
  • but if any one want to sort by question then it will not work... Commented May 29, 2020 at 11:34

2 Answers 2

6

I hope this helps -

$listItem = collect($related)->sortBy('id_question')->toArray();
Sign up to request clarification or add additional context in comments.

Comments

0

Please try:

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

1 Comment

It is still not sorted. Please help :(

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.