【发布时间】:2021-04-08 09:08:40
【问题描述】:
我在 PHP 中有一个关联数组,我想即时将其转换为 Javascript,我该怎么做?
我的 PHP 数组看起来像这样:
$pairs = ["LBo"=>"Large Blocks",
"Bo"=>"Blocks",
"bo"=>" blocky"]
我使用 JS 获取 PHP 数组大小
const pairsSize= "<?php print(count($pairs)); ?>"
接下来我创建一个循环,其中关联数组的索引名和分配的值必须从 PHP 数组中读取。我被卡住了,我不知道该怎么做。
let lithPairs = []; //my JS "associative" array
for (x = 0; pairsSize> x; x++) {
....
}
我希望结果看起来像这样;
lithPairs['LBo']="Large Blocks";
lithPairs['Bo']="Blocks";
lithPairs['bo']="blocky";
任何帮助将不胜感激!
【问题讨论】:
-
let lithPairs = []是不是关联数组。它是一个普通数组,您可以将随机对象属性附加到它。 JS中关联数组的等价物是一个对象:{} -
另外,您不需要任何循环或任何其他代码来将关联数组转换为 JS。编码为 JSON 就足够了。
-
谢谢我忘了 json
标签: javascript php arrays