Why does mysql save json in reverse order? how to fix it
P粉141925181
P粉141925181 2024-02-17 13:04:55
0
1
344

This is the code to insert json into my sql

function insert_ema($json){

$a= new Sql();
$b=$a->connection;
$sql = "INSERT INTO ema (ema_ten) VALUES ('$json')";

if ($b->query($sql) === TRUE) {
echo PHP_EOL." New record created successfully \n";
} else {
echo PHP_EOL." Error: " . $sql . "<br>" . $b->error;
}
$b->close();


;}

insert_ema('{"firstName":"John", "lastName":"Doe","3":"Jo", "4":"Do"}');

+----------------------------------------------------------------+----+
| ema_ten                                                        | id |
+----------------------------------------------------------------+----+
| {"3": "Jo", "4": "Do", "lastName": "Doe", "firstName": "John"} |  1 |
| {"3": "Jo", "4": "Do", "lastName": "Doe", "firstName": "John"} |  2 |
+----------------------------------------------------------------+----+

The sql saved above is in reverse order! ! How do I fix it

The reason I want to stick to the order is that I want to be able to convert the json to an array and use pop .

I think MySQL should save the array and sort it for this problem.

P粉141925181
P粉141925181

reply all(1)
P粉090087228

https://dev.mysql.com/doc/refman /8.0/en/json.html said:

This means that you should not rely on any specific sorting order of the keys in the JSON object. JSON arrays have order, but JSON object keys do not.

If a JSON object's keys and respective values ​​are the same, they are equal regardless of order:

mysql> select cast('{"firstName":"John", "lastName":"Doe","3":"Jo", "4":"Do"}' as json) 
  = cast('{"3": "Jo", "4": "Do", "lastName": "Doe", "firstName": "John"}' as json) 
  as is_equal;
+----------+
| is_equal |
+----------+
|        1 |
+----------+

Reply to your comment:

The point of the above example is that you cannot make MySQL store the keys in the order you want. MySQL's JSON implementation doesn't do this. It rearranges JSON object keys to improve lookup efficiency. You have no say in this.

JSON arrays can be sorted. So the only option to preserve order is to use an array, where each element of the array is an object with a single key:

[{"firstName":"John"}, {"lastName":"Doe"}, {"3":"Jo"}, {"4":"Do"}]

I know this is not what you asked for, but what you asked for is not possible in MySQL.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!