1

I have a PHP array that has a table id as the key and a table field as the value.

Example PHP:

while($row = mysql_fetch_array($result))
{
    $id = $row['id'];
    $array[$id] = $row['some_field'];
}

I then use json_encode($array) to get something like:

{"id1":"value1","abc":"123","xyz":"789"}

How can I loop through this in jQuery? From what I have found so far it seems like I need to know the key. So:

var obj = jQuery.parseJSON(jsonVar);
alert(obj.abc); //prints 123

But how can I get these values if I don't know the keys since they are dynamic?
Do I need to restructure my PHP array?

timss
  • 9,982
  • 4
  • 34
  • 56
Ryan
  • 1,135
  • 1
  • 13
  • 28

2 Answers2

3

Once you encode an associative array in php into a JSON object it is no longer an array, it is an object with keys and values. You can iterate through them in javascript using for..in

for (var key in obj) {
   console.log(obj[key]);
}

Note: for..in does not garuntee order, if you need to ensure order you will have to make your array indexed, instead of key=>value, and use a for loop (or while) instead.

JaredMcAteer
  • 21,688
  • 5
  • 49
  • 65
  • Got it. I was under the assumption that I could not use `for..in` because of [this question](http://stackoverflow.com/questions/9329446/for-each-in-a-array-how-to-do-that-in-javascript). Then I reread the part that says "for..in is for enumerating an **object's** properties", thinking I had an array. So, exactly what I needed after all. Thank you. – Ryan Apr 24 '13 at 21:57
  • Note that even though it's not considered best practice because of the ambiguity and unguaranteed sort order you can use `for..in` to loop regular arrays as well... you just *shouldn't*. – JaredMcAteer Apr 24 '13 at 22:11
3

You can get the keys of your array using Object.keys, then loop through them. Unlike for...in, this gives you the option to .sort() the keys before processing them:

var keys = Object.keys(obj).sort();  // sorting is optional
for (var i=0; i<keys.length; i++) {
    var key = keys[i],
        val = obj[key];
    console.log(key+":"+val);
};

In older browsers, you'll need a polyfill to enable the Object.keys method. MDN has one on their documentation page.

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • I got JaredMcAteer's working, but I will check this out as well. Sorting would be nice. – Ryan Apr 24 '13 at 21:53