3

My php script sends back a JSON encoded string.

I'm just lost on how to actually use the array now it sits nicely in Javascript?

The end goal is to loop through the the multi-dimensional array in JavaScript to extract values (prices)...

I've managed to get JavaScript to receive the encoded string (tested by printing it onto screen), but I'm not sure how I can actually use the array, or how I would loop through it like I would in PHP..

I basically need to do the JavaScript equivalent to this PHP code

 foreach ($array as $item => $value){

    foreach ($value as $item2 => $value2){

      //peform action on $value2;
    }
}

Thanks for any help.

Oz

2 Answers 2

2

Assuming you've called the variable arrayFromPhp, you can use a simple nested for loop:

for(var i = 0, l = arrayFromPhp.length; i < l; i++) {
  for(var j = 0, l2 = arrayFromPhp[i].length; j < l2; j++) {
    var value = arrayFromPhp[i][j];
    //Do stuff with value
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 i'm guessing he didn't know that array[i][j]; is possible.
2

Using jquery, you can iterate on a json object like that:

$.each(obj, function(key, value) {
    if ($.type(value) == "object") {
       $.each(value, function(key, value) {
           // value would be $value2 here
       })
    }
});

Also, if you get a json encoded string from PHP, you can use http://api.jquery.com/jQuery.parseJSON/ to get a json object

var obj = jQuery.parseJSON(stringFromPhp);

You can also directly use $.getJSON() (http://api.jquery.com/jQuery.getJSON/) to automatically get the json object in the callback.

edit: a parenthesis was missing.

2 Comments

This also worked for me :), however I preferred the above answer only because it more closely resembles my native language's structure of a foreach. Thanks for your time though, it's given me valuable insight into a jQuery approach. :)
No problemo :) This version feels more clean and robust to me, but it's your choice ;)

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.