Home > Article > Backend Development > After the php associative array is sorted and output to the front end using json_encode, why does the order change?
After php associative array is sorted, json_encode is used to output it to the front end. Why does the order change?
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 front desk using echo json_encode(), and the order has changed.
Why? I can't figure it out, can anyone explain it?
After php associative array is sorted, json_encode is used to output it to the front end. Why does the order change?
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 front desk using echo json_encode(), and the order has changed.
Why? I can't figure it out, can anyone explain it?
Although php arrays are ordered, JavaScript or Object in the json standard does not guarantee the order. Any change of the key by the json library is standard-compliant behavior. The processing of key order in any specific implementation (retention/sorting/shuffle ) should not be relied on
If you want to ensure the order, it is recommended to modify the data structure and use "array of object" to implement it
<code>{ cnt: [ {id: "12", value:"1"}, {id: "03", value:"1"}, ...</code>
json
is unordered
I have encountered similar problems before. You can output the value of json_encode in the form of a string. The front end can get the string and convert it yourself.
In Chrome, this does happen
Even if you output the key => value
structure in the background, the order of json_encode
is normal
However, Chrome will sort, even "string KEY" and "numeric KEY", they will all be arranged in positive order
So the final solution is
array_value