test
test

Reputation: 18200

Laravel Sort by data in JSON

Let's say I have a Model which outputs 3 models that is this data:

[
    {
        "id": 1,
        "data": [
            {
                "id": "coins",
                "qty": 3
            },
            {
                "id": "ruby",
                "qty": 52
            }
        ]
    },
    {
        "id": 2,
        "data": [
            {
                "id": "coins",
                "qty": 140
            }
        ]
    },
    {
        "id": 3,
        "data": [
            {
                "id": "coins",
                "qty": 84
            }
        ]
    }
]

How would I, using Collections, sort this data by coins's qty and who has the most.

Upvotes: 1

Views: 4058

Answers (4)

Anoop Babu
Anoop Babu

Reputation: 188

try this $array = collect($array)->sortBy('data.qty')->reverse()->toArray();

Upvotes: 0

Priyanka Patel
Priyanka Patel

Reputation: 353

A nice clean way of doing this is with the "." operator.

$projects = Project::all()->load('tasks')->sortBy('data.qty');

Upvotes: 3

Atnaize
Atnaize

Reputation: 1816

Json is mainly used as a common format for sending data.

In Laravel you can convert a json object to a php array easily by using json_decode().

$phpArray = json_decode($json);

From here you can convert it to a collection to take advantage of laravels collection functions.

$laravelArray = collect($phpArray);

After this take a look at https://laravel.com/docs/5.8/collections to do sort/filter or do whatever you want to the array.

Or you can use pure php to solve this

$json is your json retrieved

$array = json_decode($json, true);
usort($array['data'], function($a, $b) {
    return $a['qty'] <=> $b['qty'];
});

print_r($array);

Upvotes: 2

Full Stop
Full Stop

Reputation: 853

See this example code

<?php

    $json = '{
    "Message": "Done.",
    "Status": true,
    "InnerData": [
  {
     "id": 66,
     "name": "first",
     "distance": 74
  },
  {
     "id": 67,
     "name": "second",
     "distance": 153
  },
  {
     "id": 68,
     "name": "third",
     "distance": 172
  }
]
}';
$array = json_decode($json, true);
usort($array['InnerData'], function($a, $b) {
   return $a['distance'] <=> $b['distance'];
});

print_r($array);

I hope it's helps you.

Thanks.

Upvotes: 0

Related Questions