Can you share a sample of the original dataset?
It is somewhat challenging to follow from your description, without seeing the input data.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello everyone,
First of all I have managed to solve the problem in another way, but still I am curious what is happening.
So let's say I have a collection of races. Each race has equipment of type recommended or mandatory. I want to sort the equipment by type and , because it makes a lot more sense in a list view to separate the two easily.
I tried groupBy:
foreach ($races as &$race) {
$race['equipmentables'] = $race['equipmentables']->groupBy('type');
}
unset($race);
I have also tried sortBy with different combinations of array_values(), collect(), values(), toArray() without success.
foreach ($races as &$race) {
$race['equipmentables'] = array_values($race['equipmentables']->sortBy('type')->values()->toArray());
error_log(gettype($race['equipmentables']));
}
unset($race);
error_log(json_encode($races[1]['equipmentables']));
The error_log confirms that everything is good.
Unfortunately it didn't show on the website view, so now I'm testing with the following:
$data['test2'] = collect($races[1]['equipmentables'])->sortBy('type')->values()->toArray();
$data['test3'] = $races[1]['equipmentables'];
$data['test4'] = $races[1];
test2 and test3 preserve the order, test4 doesn't. But test 3 is just part of test4. What happened?
test2 and test 3:
[
{
"id": 1,
},
{
"id": 7,
},
{
"id": 8,
},
{
"id": 9,
},
{
"id": 10,
},
{
"id": 11,
},
{
"id": 12,
},
{
"id": 13,
},
{
"id": 14,
},
{
"id": 15,
},
{
"id": 16,
},
{
"id": 17,
},
{
"id": 18,
},
{
"id": 19,
},
{
"id": 2,
},
{
"id": 3,
},
{
"id": 4,
},
{
"id": 5,
},
{
"id": 6,
}
]
vs test 4
[
{
"id": 1,
},
{
"id": 2,
},
{
"id": 3,
},
{
"id": 4,
},
{
"id": 5,
},
{
"id": 6,
},
{
"id": 7,
},
{
"id": 8,
},
{
"id": 9,
},
{
"id": 10,
},
{
"id": 11,
},
{
"id": 12,
},
{
"id": 13,
},
{
"id": 14,
},
{
"id": 15,
},
{
"id": 16,
},
{
"id": 17,
},
{
"id": 18,
},
{
"id": 19,
}
]
Why does the order change in test4 and not in the others?
I've read up on json_encode and JS not preserving order, but I can't see what's the difference between $data['test3'] = $races[1]['equipmentables']; $data['test4'] = $races[1];
var_dump gives the same strange results.
var_dump($races[1]); is fine. var_dump(json_encode($races[1])); is wrong, with or without ->toArray().
What do you think?
In addition
Please or to participate in this conversation.