简体   繁体   中英

multidimensional json encoded associative array php to JS

Hi initially my array looked something like this

PHP

$results = array(
    "banana" => $bananavalue,
    "apple" => $applevalue,
);
echo json_encode($results);

JS

var fruits = [];
$.ajax({
  type: "POST",
  url: "actions/MYphp.php",
  data: PassArray,
  dataType: 'json',
  beforeSend: function (html) {
    //    alert(html);
  },
  success: function (html) {
    var obj = html;
    // Now the two will work
    $.each(obj, function (key, value) {
      fruits.push([key, value]);
    });

However I would like to change it to a multidimensional of fruits and vegetable per the below:

results = array(
    "fruit"=>array(
        "banana" => $bananavalue,
        "apple" => $applevalue
    ),
    "vegetables"=>array(
        "lettuce" => $lettuce,
        "cabbage" => $cabbage
    )
);
echo json_encode($results);

The question is how can I loop in each array in Javascript and assign it to two arrays.(fruits and vegetables)

I have tried

$.each(obj['fruit'], function(key, value) {
  fruits.push([key, value]);
});

But that didn't work.

Unlike PHP, javascript doesn't have associative arrays.

JSON-encoded PHP associative arrays decode to javascript plain objects.

To access the data in javascript :

$.ajax({
    type: "POST",
    url: "actions/MYphp.php",
    data: PassArray,
    dataType: 'json',
    success: function(obj) {
        //do whatever is required with obj.fruits and obj.vegetables here
    };
});

In general, you won't want to assign obj or obj.fruits or obj.vegetables to members in an outer scope as they are not usable until the ajax response has arrived. You will typically do everything necessary with obj.fruits and obj.vegetables in the success scope (and functions called therefrom).

do it the similar way as you would do in PHP, nest 2 loops.

$.each(obj, function(keyOfOuterArray, innerArray) {
   // keyOfOuterArray equals to vegetables, fruit
   console.log(keyOfOuterArray); 

   $.each(innerArray, function(keyOfInnerArray, valueOfInnerArray) {
     //valueOfInnerArrayis your inner array value
     console.log(keyOfInnerArray, valueOfInnerArray); 
   });
});

to answer your question do this:

var myNewObj = {};
$.each(obj, function(keyOfOuterArray, innerArray) {
   $.each(innerArray, function(keyOfInnerArray, valueOfInnerArray) {
      myNewObj[keyOfOuterArray][keyOfInnerArray] = valueOfInnerArray;
   });
});

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