需要逗号分隔json编码查询

时间:2010-12-05 19:31:28

标签: php mysql json

我正在尝试将自动填充令牌化程序脚本添加到某些表单字段中,并且在使用逗号分隔值时遇到问题。

现在,如果某人向该字段添加多个值,则自动填充建议会将它们显示为一个长值而不是每个值作为单个值。我首先尝试在编码之前爆炸该值,但它没有以正确的格式放置它。以下是它现在的显示方式:

[{"cb_activities":"Kicking Cats,"},{"cb_activities":"baseball,hockey,"}]

但我需要它显示为:

[{"cb_activities":"Kicking Cats,"},{"cb_activities":"baseball,"},{"cb_activities":"hockey,"}]

这是我的php文件:

<?
mysql_pconnect("localhost", "myuser", "mypass") or die("Could not connect");
mysql_select_db("mydb") or die("Could not select database");
$param = mysql_real_escape_string ($_GET["q"]);

$query = sprintf("SELECT DISTINCT cb_activities FROM jos_comprofiler WHERE cb_activities REGEXP '^$param'");
$arr = array();
$rs = mysql_query($query);

while($obj = mysql_fetch_object($rs))
{
    $arr[] = $obj;
}

echo json_encode($arr);
?>

这是jquery脚本: http://www.erecoverydev.com/autocomplete2/js/jquery.tokeninput.js

我对json没有做太多,所以请具体大声笑。

1 个答案:

答案 0 :(得分:0)

除非我遗漏了某些东西,否则你应该能够简单地调整你的迭代:

$activities = array();
while($obj = mysql_fetch_object($rs))
{
    $activities[] = array('cb_activities' => $obj->cb_activities);
}

但是,我只是让cb_activities成为数组,然后在js端根据需要joinsplit数组。例如:

$activities = array();

while($obj = mysql_fetch_object($rs))
{
    $activities[] = $obj->cb_activities;
}

echo json_encode(array('cb_activities' => $activities));

然后在你的js中你可以:

// assume data is the json returned by the server

var activities = data.cb_activities.join(',');