Tavi
Tavi

Reputation: 2748

Sorting key value pairs in Laravel

I have a large file containing inventories in this format:

$inventories = {"External Hard Drives":2,"Cables":1,"Disks":10,"Floppy Drives":1,"USB Sticks":5}`

I am trying to sort these by the value of each, in ascending order. I have tried:

arsort($inventories) and array_sort(inventories) without success. Any help please? I am working in Laravel 5.6.

Upvotes: 1

Views: 223

Answers (2)

KeitelDOG
KeitelDOG

Reputation: 5180

You're almost there. array_sort does not support object, but array.

$inventories = '{"External Hard Drives":2,"Cables":1,"Disks":10,"Floppy Drives":1,"USB Sticks":5}';

Now decode it with 2nd parameter true to transform into associative array.

$inventories = json_decode($inventories, true); // now you have array

Then you can do it your own way :

$inventories = array_sort($inventories); // this works

Or Use Laravel Collections approach (https://laravel.com/docs/5.6/collections#method-sort) that transforms auto for you :

$inventories = collect($inventories);
$inventories = $inventories->sort();

echo json_encode($inventories); will print :

{
    Cables: 1,
    Floppy Drives: 1,
    External Hard Drives: 2,
    USB Sticks: 5,
    Disks: 10
}

Do fancy comparison with 2 values :

$inventories = $inventories->sort(function($v1, $v2) {
    return $v2 > $v1;
});

This will print reverse :

{
    Disks: 10,
    USB Sticks: 5,
    External Hard Drives: 2,
    Cables: 1,
    Floppy Drives: 1
}

Laravel sort uses uasort in background, so you can use them directly too, but only with array as input.

Upvotes: 1

ajthinking
ajthinking

Reputation: 4558

Once you read your file you could do something like

$inventories = '{"External Hard Drives":2,"Cables":1,"Disks":10,"Floppy Drives":1,"USB Sticks":5}';

collect(json_decode($inventories))->sort();

Output

=> Illuminate\Support\Collection {#2968
     all: [
       "Cables" => 1,
       "Floppy Drives" => 1,
       "External Hard Drives" => 2,
       "USB Sticks" => 5,
       "Disks" => 10,
     ],
   }

Upvotes: 0

Related Questions