简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM