【发布时间】:2018-05-11 02:51:10
【问题描述】:
我面临一个问题,我已经尝试解决了几个小时,希望您能帮助我。所以从一开始,我就有一个 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 中一样访问每个变量,我可以运行 data[0].exercise,它给了我简单的输出“一些测试练习 1”。我试图使用例如 var_dump($data_js[0][1]);这给了我想要获得的变量,但格式如下:
object(stdClass)#2 (1) {
["exercise"]=>
string(37) "some test exercise1"
}
这远不是我想要的。我可能使用了错误的方法,第一次这样做,所以如果你们有想法或告诉我我只是做错了,我会非常高兴。似乎我迷失了整个 JS-JSON-PHP 的事情。提前谢谢你们!
【问题讨论】:
-
json_decode($data_js, true); -
var_dump($data_js[0][1]->exercise);? -
为什么不生成更合适的数组为
[{"id_day":1,"exercise":"some test exercise1","repeats":2,"energyWorth":300},..那样的话就是$data_js[$i]->exercise... -
Matteo 似乎我可以做到这一点,然后: $var1 = $data[0][1]; echo implode("",$var1);,但不确定这是否是一个好习惯@splash58 遗憾的是,它不起作用,但正如你所说,Idk 为什么我没有像你说的那样生成数组(我的错误,将修复试试你的方法)
-
@Sinner “不工作”是什么意思? - eval.in/908699
标签: javascript php arrays json ajax