将php关联数组转换为javascript对象 [英] convert php associative array into javascript object

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

问题描述

我正在尝试将中文单词作为键加载,将它们的英文翻译作为数据库中的值加载到php数组中,这样我就可以在JavaScript的客户端使用它们了。所以我将PHP密钥:值对加载到JavaScript数组中,并尝试将结果作为键值对输出:

I'm trying to load Chinese words as keys, and their English translations as values from a database into a php array so then I can use them on the client side in JavaScript. So I load the PHP key:value pairs into the JavaScript array and try to output the results as key value pair as such:

stuff : Ni, You 
stuff : Ta, Him or Her
stuff : Wo, I

中文和英文单词加载在关系数据库中。

Chinese and English words are loaded in a relational database.

PHP

$wordsArray = array();               
while ($row = $sql->fetch_assoc()) {
    $wordsArray[$row['chinese']] = $row['english'];
}

Javascript :这里我想要$ .each将密钥输出为字符串,而不是数字索引。所以当我尝试 var words = [<?php echo''。implode(',',$ wordsArray)。'''?>]; 作为一个数组,我得到了:

Javascript: Here I want the $.each to output the key as a string, and not a number index. So when I tried var words = [<?php echo '"'.implode('","', $wordsArray).'"' ?>]; as an array, I got:

stuff : 0, You 
stuff : 1, Him or Her
stuff : 2, I

当我真的在寻找:

stuff : Ni, You 
stuff : Ta, Him or Her
stuff : Wo, I

所以我将改为对象,以便 $ .each 可以将键输出为字符串:

So I changed words to be an object so that $.each could output key as string:

var words = {<?php echo '"'.implode('","', $wordsArray).'"' ?>};
$.each(words, function(key, value) {
    console.log('stuff : ' + key + ", " + value);
});

抛出错误: SyntaxError:意外的令牌,

推荐答案

您可以使用 json_encode()使数组作为 json对象喜欢,

You can use json_encode() to make array as an json object like,

var words = <?php echo json_encode($wordsArray) ?>;// don't use quotes
$.each(words, function(key, value) {
    console.log('stuff : ' + key + ", " + value);
});

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

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