Athanatos
Athanatos

Reputation: 1089

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.

Upvotes: 0

Views: 1981

Answers (2)

Beetroot-Beetroot
Beetroot-Beetroot

Reputation: 18078

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

Upvotes: 1

GGio
GGio

Reputation: 7653

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

Upvotes: 0

Related Questions