1

In my code, i have a collection object. One part of the collection object is structured as follows

"id" => 1
"rate" => "{"p_1":"1","p_2":"2","p_3":"2.3","p_4":"3.5"}"
"currency" => 1
"desc" => "TEST"

In the above instance i have a key called rate, which has a json string as value.

What i want to do is sort the collection object by value p_1 contained in the range key.

5
  • Your question is unclear. In what way do you want to order p_1 in rate? Commented Oct 25, 2017 at 13:15
  • What Laravel version are you using? Commented Oct 25, 2017 at 13:17
  • @NicolaWorthington i want to order all the objects of the collection by the p_1. Commented Oct 25, 2017 at 13:19
  • @Jerodev i am using laravel 5.4 Commented Oct 25, 2017 at 13:19
  • @AMDEV : did you fixed this issue ? Commented Oct 26, 2017 at 11:25

2 Answers 2

2

You have to decode the JSON string before ordering:

$collection->sortBy(function(array $item) {
    return json_decode($item->rate)->p_1;
});
Sign up to request clarification or add additional context in comments.

Comments

1

Use sortBy() to sort collection in laravel

$collection->sortBy(function($item) {
  return $item->rate->p_1;
});

here $collection is your laravel result which gives by default, you can explicitly convert it by using collect method as well

Check docs for more details

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.