【发布时间】:2014-08-02 06:50:32
【问题描述】:
我有一个 PHP 数组 ($cloud),在使用 json_encode 后,当我打印它时返回以下内容:
该数组现在包含正确的内容,但看起来与我需要的不同,这可能是为什么在我的 JS 中使用它不起作用。
当前数组如下(缩短):
Array ( [0] => Array ( [text] => item 1 [weight] => 20 ) [1] => Array ( [text] => item 2 [weight] => 19 ) [2] => Array ( [text] => item 3 [weight] => 18 ) [3] => Array ( [text] => item 4 [weight] => 17 ) [4] => Array ( [text] => item 5 [weight] => 16 ) )
有没有办法可以将其转换为如下所示的 JavaScript 数组,这是我需要的函数?
var word_array = [
{text: "item 1", weight: 20},
{text: "item 2", weight: 19},
{text: "item 3", weight: 18},
{text: "item 4", weight: 17},
{text: "item 5", weight: 16},
];
很遗憾,我无法在此处提供更多信息,因为我不知道如何做到这一点。 我尝试将其简单地回显到 JS 变量中,但这不起作用,因为格式不是函数所期望的。
非常感谢蒂姆的任何提示。
【问题讨论】:
-
它实际上将数组返回为您的格式...但是如果 js 无法识别它,那么您可以使用 eval(yourphpencodedarray) 或 JSON.parse(yourphpencodedarray)
-
谢谢!我将如何在这里使用它?
-
你需要使用
JSON.parse(array)在javascript中使用它。示例:
标签: javascript php arrays loops