skip to Main Content

I have this json value that I want to be sorty but for some reason it’s not working.

    [
        {
            "id": 15028,
            "order_id": 342,         
            "user_id": 3,
            "status": "1",
            "priority": "1",
            "donedate": null,
            "user": {
                "id": 3,
                "name": "Max"
            }
        },
        {
            "id": 15030,
            "order_id": 341,         
            "user_id": 4,
            "status": "2",
            "priority": "1",
            "donedate": null,
            "user": {
                "id": 4,
                "name": "Jon"
            }
        }
    ]

This jSon structure is the result of Laravel eloquent object conversion using $object->toJson();

Now I keep this output in my Redis cache. What I want is to when the status and or priority of any order gets changed then I want to sort this jSon and store it back in Redis.

$order_list = collect($json_decoded_with_updated_values);
$order_list = $order_list->sortBy('status')->sortBy('priority');
Redis::set(GuzzleHttpjson_encode($stich_list_in_collection));
Redis::set("orders_list", $orders_list, 302400);

However, I don’t get a sort list. What I want to achieve is that, just like I would run two to three orderBy on an eloquent model like orderBy(‘status’)->orderBy(‘priority’)->get() .. I want to run the same two sortings on this json list.

Thanks in advance.

3

Answers


  1. Chosen as BEST ANSWER

    I figured it out. Actually we don't need to have a call-back as suggested by @brokedid. We can do it like following.

    $order_list->sortBy('status')->sortBy('priority')->values()->all();
    

    So I was missing the "->values()->all()" part. I hope if any one runs into the same problem in future, they can get a hint from this.


  2. I wonder what’s the result when you choose a different sort direction.

    $order_list = $order_list->sortByDesc('status');
    
    Login or Signup to reply.
  3. If you want to sort by multiple Fields, then you could try to sort with a callback-method:

    $orderedList = $unorderedList->sortBy(function($item) {
      return $item->priority.'-'.$item->status;
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search