mmccaff
1 month ago
154
4
Laravel

Custom sorting of collection's json object attribute

Posted 1 month ago by mmccaff

I have a json_metrics attribute belonging to an item in a collection. (it's actually a column in a database, but I think it's going to be easier to sort in code than in the database.. )

The data in json_metrics is an array of objects, with each having a sessions, entrances, month and year attributes. There is at most one object in the array per month/year combination, but possibly none. So it looks like this, for example:

[
  {"sessions":52,"entrances":55,"month":3,"year":2020},
  {"sessions":59,"entrances":59,"month":4,"year":2020},
  {"sessions":76,"entrances":76,"month":5,"year":2020}
]

I would like to be able to sort items in the collection on either "sessions" or "entrances" for a given "month" and "year" combination stored in this json_metrics attribute. eg. Sort the items by descending 3/2020 sessions.

Can anyone help me with this?

Please sign in or create an account to participate in this conversation.