2015-03-02 20 views
1

我已经在SQL数据库中的以下数据如何使用PHP分配键:从SQL到JavaScript对象的值对?

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"}] 

回答

1

变化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']; 
} 
2

改变这种代码

while($r2 = mysql_fetch_assoc($result2)) { 
    $rows2[] = $r2; 
} 

这一个:

while($r2 = mysql_fetch_assoc($result2)) { 
    $rows2[$r2['ccode']] = $r2['colour']; 
}