如何使用 PHP 将 key:value 对从 SQL 分配给 JavaScript 对象?
How to assign key:value pairs from SQL to JavaScript Object using PHP?
我在 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); ?>';
哪个returns:
[{"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'];
}
更改 php 其他答案中的代码,它应该像
$rows2 = array();
while($r2 = mysql_fetch_assoc($result2)) {
$rows2[$r2['ccode']] = $r2['colour'];
}
如果它不起作用,那么试试这个:
$rows2 = array();
while($r2 = mysql_fetch_assoc($result2)) {
$rows2["'".$r2['ccode']."'"] = $r2['colour'];
}
如果还是不行,试试这个:
$rows2 = array();
while($r2 = mysql_fetch_assoc($result2)) {
$rows2[{$r2['ccode']}] = $r2['colour'];
}
我在 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); ?>';
哪个returns:
[{"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'];
}
更改 php 其他答案中的代码,它应该像
$rows2 = array();
while($r2 = mysql_fetch_assoc($result2)) {
$rows2[$r2['ccode']] = $r2['colour'];
}
如果它不起作用,那么试试这个:
$rows2 = array();
while($r2 = mysql_fetch_assoc($result2)) {
$rows2["'".$r2['ccode']."'"] = $r2['colour'];
}
如果还是不行,试试这个:
$rows2 = array();
while($r2 = mysql_fetch_assoc($result2)) {
$rows2[{$r2['ccode']}] = $r2['colour'];
}