将 PHP 数组转换为 JavaScript 数组
我想将多维 PHP 数组转换为 JavaScript,并在此处的帖子中找到了此脚本;
<script type='text/javascript'>
<?php
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
?>
</script>
但 JS 数组仍然是空的。是因为我有一个多维数组吗?
I want to convert a multi-dimensional PHP array to JavaScript and found this script in a post here;
<script type='text/javascript'>
<?php
$js_array = json_encode($php_array);
echo "var javascript_array = ". $js_array . ";\n";
?>
</script>
But the JS array remains empty. Is it because I have a multi-dimensional array?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
根据您对其中一个答案的评论,您确定 $js_array 是空的还是您只是没有解码它?如果您查看生成的 JavaScript,您会看到
var javascript_array = ;
或其他内容吗?或者,您可以添加alert( javascript_array );
进行检查。编辑:由于变量没问题,您现在可以使用
javascript_array[0].id
、javascript_array[0].question
等访问元素。Based on the comment you gave to one of the answers, are you sure
$js_array
is empty or are you just not decoding it? If you look at the generated JavaScript, do you seevar javascript_array = ;
or something else? Alternatively you could addalert( javascript_array );
to check.EDIT: Since the variable is ok, you can now access the elements with
javascript_array[0].id
,javascript_array[0].question
etc.您还可以尝试更多手动操作,如下所示:
You can also try something more manual like this:
如果
$php_array
不为空,请尝试......而不是:
希望有帮助! :)
If
$php_array
isn't empty, try to......instead of:
Hope it helps! :)
您可能必须评估该 json,才能使其不仅仅是 JavaScript 代码中的字符串。
You probably have to eval that json in order for it to be more than just a string in your JavaScript code.