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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Got it. I was under the assumption that I could not use for..in because of this question. 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.
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.
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.

1 Comment

I got JaredMcAteer's working, but I will check this out as well. Sorting would be nice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.