Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mihirpatel83's avatar

JSON Field order changes while saving

I am using a json Field to store multiple values of a dropdown. The array is like

["Male"=>"Male","Female"=>"Female","Test"=>"Test"]

but when I check the values in database after saving in JSON field it is of below format.

{"Male": "Male", "Test": "Test", "Female": "Female"}

Upon searching a bit it seems that MySql sorts them. What could be a possible solution to overcome these?

0 likes
10 replies
mihirpatel83's avatar

@ATHAKUR - I am using casting only but I guess the link doesn't answers my question. The order gets changed on saving which I don't want. Need to know a way to maintain the order of the values that are stored.

1 like
mihirpatel83's avatar

@ATHAKUR - Yes I read that and which essentially is not the way most usecases want that. Hence want to know a workaround for that.

One thing is storing some kind of extra ordering no with each value but that will be extra work to parse it. That's the solution I can think of at the moment.

bobdebower's avatar

I have the same problem, why isn't there any solution for this? it's really annyoing because i need the data the why i store it.

bobdebower's avatar

Ok i think i found a solution. instead of saving the data as json-> save it as text

1 like
hamstar's avatar

@bobdebower Becuase some mysql version json() schema save as json, and others save as longtext automatically.

gradientps's avatar

Solution I'm using to overtime this is to save the keys in order as an array using array_keys($data) along with the data in the json object.

$data = ["Male"=>"Male","Female"=>"Female","Test"=>"Test"];
$data["sort_order"] = array_keys($data);

On the frontend, I then just loop over the $data->sort_order to know the order in which to display the information.

Hope that helps.

1 like

Please or to participate in this conversation.