In PHP I’m running a mysql_query that has an ORDER BY clause. I’m then iterating through the results to build an associative array, with the row_id as the key.
Then, I’m calling json_encode on that array and outputting the result.
This page is loaded with AJAX, and defined in a Javascript variable. When I iterate through that Javascript variable, will I still have the order that was returned from the mysql_query?
What cletus says is correct, but in my experience, most browsers will maintain the order. That being said, you should consider using an
Array. If you need to sort it once you receive it on the client-side, just use the.sort()function in JavaScript:Though it seems like it works, the order of properties in an object can’t be counted on. See the many comments below for more info (smarter eyes than mine). However, this was the code I used to test the behavior in my own limited testing:
Prints (in Firefox 3.6.3 and Chrome 5.0.375.9):
Also, you may want to be sure you’re getting the type of JSON encoding you’re needing back from
json_encode(), such as an object (uses{}curly braces) and not an array ([]braces). You may need to passJSON_FORCE_OBJECTtojson_encode()to force it.Arrayapproach is preferred)