Unable to return sorted array in Laravel with preserved keys

  laravel, laravel-5.8, laravel-collection, php

I have below array:

$arr[123]['price'] = 100;
$arr[456]['price'] = 500;
$arr[100]['price'] = 1000;
$arr[511]['price'] = 200;

Now I want to sort it by price, so I did below operation:

$arr = collect($arr);

$sorted = $arr->sortBy('price');

Array gets sorted & dd($sorted) gives me below result:

Collection {#957 ▼
  #items: array:4 [▼
    123 => array:1 [▼
      "price" => 100
    ]
    511 => array:1 [▼
      "price" => 200
    ]
    456 => array:1 [▼
      "price" => 500
    ]
    100 => array:1 [▼
      "price" => 1000
    ]
  ]
}

But when I return above sorted array, it gets sort again by keys:

return $sorted;

Above outputs:

{
  "100": {
    "price": 1000
  },
  "123": {
    "price": 100
  },
  "456": {
    "price": 500
  },
  "511": {
    "price": 200
  }
}

I know values() will solve this but I do not want reindexing. I want returned array in below format only:

{
      "123": {
        "price": 100
      },
      "511": {
        "price": 200
      },
      "456": {
        "price": 500
      },
      "100": {
        "price": 1000
      }
    }

Does any one have any idea how do I get this? I also tried $preserveKeys flag but no success.

I am using Laravel 5.8.35

Source: Laravel StackOverflow

Leave a Reply