开发者

placing a multi-dimensional array into Javascript from PHP using JSON

My php script sends back a JSON encoded string.

I'm just lost on how to actually use the ar开发者_运维问答ray 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


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
  }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜