Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine json_array config wrong order in keys

I have this weird problem with the json_array field configuration.

I have configured field meant to store some configuration. Its configured like this:

<field name="config" type="json_array" />

For example, I have an array like this:

[
    'choices' => [
        'Other' => 'other',
        'Male' => 'male',
        'Female' => 'female'
    ]
]

I set the entity property:

$entity->setConfig($config);

And I persist it to the database. The result is this:

"choices": {
    "Male": "male",
    "Other": "other", 
    "Female": "female"
}

When I do json_encode on the same array, the order is not changed, but somehow Doctrine does change the order. Is there a way to prevent this from happening?

like image 344
Dion Snoeijen Avatar asked Oct 20 '25 02:10

Dion Snoeijen


2 Answers

Using one of the enumerated versions will prevent this behaviour:

$v1 = [
    'choices' => [
        'Other',
        'Male',
        'Female'
    ]
];

$v2 = [
    'choices' => [
        ['label' => 'Other', 'value' => 'other'],
        ['label' => 'Male', 'value' => 'male'],
        ['label' => 'Female', 'value' => 'female']
    ]
];

More information you can find here Does JavaScript Guarantee Object Property Order?

like image 53
vpalade Avatar answered Oct 21 '25 17:10

vpalade


Doctrine docs states this :

You should never rely on the order of your JSON object keys, as some vendors like MySQL sort the keys of its native JSON type using an internal order which is also subject to change.

like image 39
Roubi Avatar answered Oct 21 '25 17:10

Roubi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!