After the PHP associative array is sorted, output to the front end with Json_encode, why is the order changed?

Source: Internet
Author: User

After the PHP associative array is sorted, output to the front end with Json_encode, why is the order changed?
This is a sorted array written to the file using the File_put_contents function, which is the right order.


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

Why is it? Can't think of, who can answer.

Reply content:

After the PHP associative array is sorted, output to the front end with Json_encode, why is the order changed?
This is a sorted array written to the file using the File_put_contents function, which is the right order.


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

Why is it? Can't think of, who can answer.

Although the array of PHP is orderly, JavaScript or JSON standard object is not guaranteed order, the JSON library arbitrarily change key is a standard behavior, any particular implementation of the key sequence of processing (reservation/ordering/disorderly) should not be relied on

If you want to guarantee the order, we recommend modifying the data structure with "array of object" implementation

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

jsonIt's disordered.

Before you meet a similar problem, you can put the value of the Json_encode in the form of a string output, the front end to get a string of their own conversion processing to try

In Chrome, that's really the case.

Even if you output the structure in the background key => value , the json_encode order is normal.

However, Chrome will sort, even if it's "string key", "The digital key", all in a positive order

So the ultimate 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.