用于发送到Php的Javascript对象到数组转换

时间:2012-09-18 04:28:46

标签: php javascript arrays object

我有一个javascript dynimic数组创建器代码,如下所示

function createArray() {

    var myArr = new Object();
    myArr[0] = createSubArray('apple');
    myArr[1] = createSubArray('Mango');
    myArr[2] = createSubArray('Pineapple');
    myArr[3] = createSubArray('Grape');
    document.getElementById("a").innerHTML = JSON.stringify(myArr);
    return myArr;

}


function createSubArray(name){
    var arr = new Object();
    elems = document.getElementsByName(name);
    for (var i=0;i<elems.length;i++){
        if (elems[i].checked){
            arr[name] =  elems[i].value;
            arr['price'] =  elems[i].getAttribute('data-price');
        }
    }
    return arr;
   }

在此代码中,我需要将值作为array而不是object发送。 我尝试在new Object();函数中更改new Array();createArray,但当我json_decode得到如下结果时

array
  0 => 
    object(stdClass)[1]
      public 'apple' => string 'light' (length=5)
      public 'price' => string '10' (length=2)
  1 => 
    object(stdClass)[2]
      public 'Mango' => string 'light' (length=5)
      public 'price' => string '30' (length=2)
  2 => 
    object(stdClass)[3]
      public 'Pineapple' => string 'light' (length=5)
      public 'price' => string '50' (length=2)
  3 => 
    object(stdClass)[4]
      public 'Grape' => string 'dark' (length=4)
      public 'price' => string '80' (length=2)

如果我在createSubArray函数中更改新的对象,我不会得到任何值.. 请检查下面

new Object changed to new Array in createArray function

new Object changed to new Array in createArray And createSubArray function

如何将对象更改为数组?

请帮我解决这个问题

1 个答案:

答案 0 :(得分:4)

$array = json_decode($json, true);

将第二个参数设置为true强制json_decode以返回关联数组而不是stdClass