Why does the order change when json_encode is output to the front end after the php array is sorted?

Source: Internet
Author: User
Why does the order change when json_encode is output to the front end after the php array is sorted? This is the sorted array written to the file using the file_put_contents function. The order is correct. This is the data output to the foreground using echojson_encode (), and the order has changed. Why...

Why does the order change when json_encode is output to the front end after the php array is sorted?
This is the sorted array written to the file using the file_put_contents function. The order is correct.


This is the data output to the foreground using echo json_encode (), and the order has changed.

Why? I cannot figure it out. who can answer it.

Reply content:

Why does the order change when json_encode is output to the front end after the php array is sorted?
This is the sorted array written to the file using the file_put_contents function. The order is correct.


This is the data output to the foreground using echo json_encode (), and the order has changed.

Why? I cannot figure it out. who can answer it.

Although php arrays are ordered, objects in javascript or json standards do not guarantee the order, any changes to keys in the json Library comply with the standard behavior, the processing of key order (retained/sorted/out-of-order) in any specific implementation should not be dependent

To ensure the order, we recommend that you use "array of object" to modify the data structure.

{  cnt: [    {id: "12", value:"1"},    {id: "03", value:"1"},    ...

jsonIs unordered

You have encountered a similar problem before. you can output the json_encode value in the form of a string. the front end can get the string and convert it by yourself.

In Chrome, this is indeed the case.

Even if you outputkey => valueStructure,json_encodeThe order is normal.

However, Chrome will sort, even if it is a "string KEY" or "number KEY", in a forward order.

So the final solution is

array_value

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.