将多维PHP数组转换为javascript数组 [英] Convert Multidimensional PHP array to javascript array

查看:96
本文介绍了将多维PHP数组转换为javascript数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用JSON编码器将PHP多维数组转换为javascript数组。当我做一个var_dump时,我的php数组看起来像这样:

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:

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

这是我目前使用的代码我尝试将其转换为JavaScript数组的观点:

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

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"}]);

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

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

SyntaxError:意外的令牌o

推荐答案

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

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

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

您应该可以访问这些属性

You should be able then to access the properties as

alert(tempArray[0].Key);

这篇关于将多维PHP数组转换为javascript数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆