Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will the Order of my Associative Array be maintained from PHP to Javascript?

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?

like image 523
Colin Avatar asked Apr 22 '10 01:04

Colin


2 Answers

PHP arrays are somewhat unique in their property of maintaining insertion order. Javascript doesn't have associative arrays per se. It has objects, which are often used as associative arrays. These do not guarantee any particular key order.

Why not output them as an array? That will have a particular order. If you want some sort of key lookup why does the order matter?

like image 90
cletus Avatar answered Nov 04 '22 23:11

cletus


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:

rows.sort(function(a, b) {
    return a.row_id - b.row_id;
}

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:

var test = {
    one: 'blah',
    two: 'foo',
    another: 'bar'
};

for (prop in test) {
    document.write(prop + "<br />");
}

Prints (in Firefox 3.6.3 and Chrome 5.0.375.9):

one
two
another

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 pass JSON_FORCE_OBJECT to json_encode() to force it.

  • Edited to clarify that the Array approach is preferred)
  • Edited again (sorry), as I had overlooked pcorcoran's comment, which has a link to an issue in Chromium's issue tracker regarding this. Suffice to say, the order an object's properties is not reliable.
like image 34
awgy Avatar answered Nov 04 '22 23:11

awgy