将数组从php查询转换为可用的javascript格式

将数组从php查询转换为可用的javascript格式,javascript,php,arrays,Javascript,Php,Arrays,如何从查询中获取php数组,并使其看起来像这样: ["14-11-2016","15-11-2016"] 我试过这样做: $result=$connection->query("select day from blockades"); while($row=mysqli_fetch_assoc($result)){ echo json_encode($row['day']); echo ","; } 它给了我: "1-11-2016","2-11-2016","3-11-2016","

如何从查询中获取php数组,并使其看起来像这样:

["14-11-2016","15-11-2016"]
我试过这样做:

$result=$connection->query("select day from blockades");
while($row=mysqli_fetch_assoc($result)){
echo json_encode($row['day']);
echo ",";
}
它给了我:

"1-11-2016","2-11-2016","3-11-2016","4-11-2016",
但当我尝试将其放入javascript数组时

var Array=<?php 
    while($row=mysqli_fetch_assoc($result)){
    echo json_encode($row['day']);
} 
?>
console.log(Array)
由于console.log没有提供任何信息,我不知道它是否向js数组写入了任何内容,有人能帮忙吗?

查看您的错误

未捕获的TypeError:无法读取未定义的属性“prototype”

似乎您已经更改了
数组的原型,这可能是因为使用了

var Array=<?p
然后

console.log(arr);

问题是您正在对每个单独的项进行编码,但需要对整个项列表进行编码

<?php
// Create array to hold all items.
$days = array();
$result = $connection->query("select day from blockades");
// Add the days to the array.
while($row = mysqli_fetch_assoc($result)){
    $days[] = ($row['day']);
}

// Output the JavaScript variable:
?>
<script type="text/javascript">
var Days=<?php echo json_encode($days) ?>;
console.log(Days);
</script>

var天数=;
控制台日志(天);

现在错误变为“undefined”,这是否意味着我的arr为空?@Bonana可能是,请在开发人员工具中检查此php代码的输出。是Javascript中的全局对象。同样,对于格式良好的js数组,您缺少
[
]
。并且不要手动构建数组。在PHP中构建所需的数组,并立即对整个内容进行编码
$arr=Array();而($row=mysqli_fetch_assoc($result))$arr[]=$row['day';echo json_编码($arr)
console.log(arr);
<?php
// Create array to hold all items.
$days = array();
$result = $connection->query("select day from blockades");
// Add the days to the array.
while($row = mysqli_fetch_assoc($result)){
    $days[] = ($row['day']);
}

// Output the JavaScript variable:
?>
<script type="text/javascript">
var Days=<?php echo json_encode($days) ?>;
console.log(Days);
</script>