从JS到PHP的对象数组

时间:2017-11-27 19:11:33

标签: javascript php arrays json ajax

我正面临一个问题,我已经尝试解决了几个小时,我希望你能帮助我。所以从一开始,我就有一个JavaScript算法,它生成我想保存到数据库并在网站上打印给用户的变量。要做到这一点,我认为我将生成一个对象数组来同时处理所有变量(它生成尽可能多的变量,因为有时它可能只有少数,有时甚至几倍)。我认为使用json发送和处理很容易,然后可以在PHP中作为普通变量访问。所以这是我的测试数据:

[[{"id_day":1},{"exercise":"some test exercise1"},{"repeats":2},{"energyWorth":300}],
[{"id_day":1},{"exercise":"some test exercise2"},{"repeats":2},{"energyWorth":300}],
[{"id_day":2},{"exercise":"some test exercise3"},{"repeats":2},{"energyWorth":300}],
[{"id_day":2},{"exercise":"some test exercise4"},{"repeats":2},{"energyWorth":300}],
[{"id_day":3},{"exercise":"some test exercise5"},{"repeats":2},{"energyWorth":300}],
[{"id_day":3},{"exercise":"some test exercise6"},{"repeats":2},{"energyWorth":300}],
[{"id_day":4},{"exercise":"some test exercise7"},{"repeats":2},{"energyWorth":300}],
[{"id_day":4},{"exercise":"some test exercise8"},{"repeats":2},{"energyWorth":300}],
[{"id_day":5},{"exercise":"some test exercise9"},{"repeats":2},{"energyWorth":300}],
[{"id_day":5},{"exercise":"some test exercise10"},{"repeats":2},{"energyWorth":300}],
[{"id_day":6},{"exercise":"some test exercise11"},{"repeats":2},{"energyWorth":300}],
[{"id_day":6},{"exercise":"some test exercise12"},{"repeats":2},{"energyWorth":300}]]

我在我的脚本中使用了ajax来通过以下代码发送这个对象数组:

$.ajax({
    url: 'test2.php',
    type: 'post',
    data: {"data_js" : JSON.stringify(plan)},
    success: function(data) {

    }
});

并希望通过运行代码

在名为test2.php的PHP文件中使用em
if (isset($_POST["data_js"])) {
$data_js = $_POST["data_js"];
$data_js = json_decode($data_js);

var_dump($data_js);
var_dump($data_js[0][1]);
}

所以我已成功将我的对象数组发送到名为$ data_js的变量,并使用json解码em以在PHP中使用em。问题是我的数组现在看起来像这样:

array(20) {
  [0]=>
  array(4) {
    [0]=>
    object(stdClass)#1 (1) {
      ["id_day"]=>
      int(1)
    }
    [1]=>
    object(stdClass)#2 (1) {
      ["exercise"]=>
      string(37) "some test exercise1"
    }
    [2]=>
    object(stdClass)#3 (1) {
      ["repeats"]=>
      int(2)
    }
    [3]=>
    object(stdClass)#4 (1) {
      ["energyWorth"]=>
      int(300)
    }
  }
  [1]=>
  array(4) {
    [0]=>
    object(stdClass)#5 (1) {
      ["id_day"]=>
      int(1)
    }
    [1]=>
    object(stdClass)#6 (1) {
      ["exercise"]=>
      string(38) "some test exercise2"
    }
    [2]=>
    object(stdClass)#7 (1) {
      ["repeats"]=>
      int(2)
    }
    [3]=>
    object(stdClass)#8 (1) {
      ["energyWorth"]=>
      int(300)
    }
  }

等等。问题是我必须访问每个变量,就像在JS中我可以运行数据[0] .exercise,它给了我简单的输出“一些测试练习1”。我试图使用例如var_dump($ data_js [0] [1]);这给了我想要的变量,但是采用这种格式:

object(stdClass)#2 (1) {
  ["exercise"]=>
  string(37) "some test exercise1"
}

这远不是我想要的。我可能会使用错误的方法,这是第一次这样做,所以如果你们有想法或告诉我,我只是做错了我会非常高兴。似乎我迷失在整个JS-JSON-PHP中。提前谢谢你们!

0 个答案:

没有答案