我在 SQL 数据库中有以下数据
cname, ccode, colour
Great Britain, GB, 1
Italy, IT, 1
France, FR, 1
Spain, ES, 1
如何创建如下所示的 JavaScript 对象?
var countries = {"GB":1, "IT":1, "FR":1, "ES":1}
到目前为止,我有以下代码;
PHP
$query2 = "SELECT ccode,colour FROM country_data WHERE 1";
$result2 = mysql_query($query2);
if (!$result2) {
die('Invalid query: ' . mysql_error());
}
$rows2 = array();
while($r2 = mysql_fetch_assoc($result2)) {
$rows2[] = $r2;
}
JS
var colours = '<?php print json_encode($rows2); ?>';
哪个返回:
[{"ccode":"GB","colour":"1"},{"ccode":"IT","colour":"1"},{"ccode":"FR","colour":"1"},{"ccode":"ES","colour":"1"}]
最佳答案
更改此代码
while($r2 = mysql_fetch_assoc($result2)) {
$rows2[] = $r2;
}
这个:
while($r2 = mysql_fetch_assoc($result2)) {
$rows2[$r2['ccode']] = $r2['colour'];
}
关于javascript - 如何分配 key :value pairs from SQL to JavaScript Object using PHP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28809293/