[英]Why does PHP json_encode flatten array?
I have this PHP array ( $savedRequestDates
) of dates: 我有这个日期的PHP数组(
$savedRequestDates
):
Array ( [0] => 2018-03-29 10:56:31 [1] => 2018-03-29 10:58:09 [2] => 2018-04-12 11:28:41 [3] => 2018-04-12 13:07:25 [4] => 2018-05-09 13:08:07 )
At the bottom of the same .php page I have this: 在同一.php页面的底部,我有这个:
<script type="text/javascript">
var sessions = new Array('<?php echo json_encode($savedRequestDates); ?>');
console.log(sessions[0]);
</script>
The console.log(sessions[0]);
console.log(sessions[0]);
returns: 收益:
["2018-03-29 10:56:31","2018-03-29 10:58:09","2018-04-12 11:28:41","2018-04-12 13:07:25","2018-05-09 13:08:07"]
Why is the JavaScript array flattening at the 0 index? 为什么JavaScript数组在0索引处变平? If I try
console.log(sessions);
如果我尝试
console.log(sessions);
it returns an array with one variable, not 5, as the php array clearly shows. 它返回一个带有一个变量而不是5的数组,如php数组清楚所示。
Am I missing something here? 我在这里想念什么吗?
This happens because you're wrapping the array from PHP which another array ( new Array
). 发生这种情况是因为您要包装PHP中的另一个数组(
new Array
)。 Just remove the new Array
part and it will work fine. 只需删除
new Array
部件即可正常工作。
var sessions = <?php echo json_encode($savedRequestDates); ?>;
From what I see the call to json_encode
will create a full JSON object and not just the content of the array. 从我看到的结果来看,对
json_encode
的调用将创建一个完整的JSON对象,而不仅仅是数组的内容。 You are enclosing the entire output of the PHP generated array as index 0 inside the new Array
. 您会将PHP生成的数组的整个输出包含在
new Array
作为索引0。
So removing the new Array
will generate what you are looking for. 因此,删除
new Array
将生成您想要的东西。
Try this: 尝试这个:
<script type="text/javascript">
var sessions = <?php echo json_encode($savedRequestDates); ?>;
console.log(sessions);
</script>
And you should see the entire array. 您应该看到整个阵列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.