将多维 PHP 数组转换为 javascript 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17048140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:53:59  来源:igfitidea点击:

Convert Multidimensional PHP array to javascript array

phpjavascript

提问by user1186173

I'm trying to convert a PHP multidimensional array to a javascript array using the JSON encoder. When I do a var_dump, my php array looks like this:

我正在尝试使用 JSON 编码器将 PHP 多维数组转换为 javascript 数组。当我执行 var_dump 时,我的 php 数组如下所示:

array (size=2)
  'Key' => string 'a' (length=1)
  'Value' => string 'asite.com' (length=9)

This is the code I'm currently using in my view to try to convert it to a JavaScript array:

这是我目前在我看来尝试将其转换为 JavaScript 数组的代码:

var tempArray = $.parseJSON(<?php echo json_encode($php_array); ?>);

Whenever I run this code in the browser, the output of the conversion in the console is this:

每当我在浏览器中运行此代码时,控制台中的转换输出是这样的:

var tempArray = $.parseJSON([{"Key":"a","Value":"asite.com"}]);

Is this the correct structure for a javascript multidimensional array? I'm asking because it keeps giving me this error on the line above:

这是 javascript 多维数组的正确结构吗?我问是因为它在上面的行中不断给我这个错误:

SyntaxError: Unexpected token o

SyntaxError: Unexpected token o

回答by Orangepill

You do not have to call parseJSON since the output of json_decode is a javascript literal. Just assign it to a variable.

您不必调用 parseJSON,因为 json_decode 的输出是 javascript 文字。只需将其分配给一个变量。

var tempArray = <?php echo json_encode($php_array); ?>;

You should be able then to access the properties as

然后您应该能够访问这些属性

alert(tempArray[0].Key);

回答by SergioMC

This worked for me.

这对我有用。

<script type='text/javascript'>
<?php
    $php_array = array(
        array("casa1", "abc", "123"), 
        array("casa2", "def", "456"), 
        array("casa3", "ghi", "789" )
    );

    $js_array = json_encode($php_array);
    echo "var casas = ". $js_array . ";\n";
?>

alert(casas[0][1]);

</script>

回答by sandino

Do not use parseJSON, that's for a string. Just do:

不要使用 parseJSON,这是一个字符串。做就是了:

<?php
$php_array = array ('Key'=>'a', 'Value'=>'asite.com');
?>
<html>
<head>

    <script type="text/javascript">
    var tempArray = <?php echo json_encode($php_array); ?>;
    console.log(tempArray);
    </script>
</head>
<body>
</body>
</html>

This give me in the console:

这在控制台中给了我:

Object { Key="a", Value="asite.com"}

回答by Fly_pig

Just add single quotes in the js function,like

只需在 js 函数中添加单引号,例如

var tempArray = $.parseJSON('<?php echo json_encode($php_array); ?>');

var tempArray = $.parseJSON('<?php echo json_encode($php_array); ?>');