0

我最近开始为一个新项目使用 twitter typeahead 插件并且遇到了一些障碍,我正在查询 1 个表中的 2 列以搜索要搜索的数据,我只搜索 1 列时它工作正常但是当移动到二我相信我需要开始使用令牌进行搜索。

但是我想不出一种方法将令牌添加到我的数组中,然后将它们编码为 json 并返回搜索

到目前为止,这是我的代码:

$dbh = new PDO('mysql:host=127.0.0.1;dbname=test', 'root', '');

$stmt = $dbh->prepare('SELECT NAME, CLID FROM customer');
$stmt->execute();

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $row_array['NAME'] = $row['NAME'];
    $row_array['CLID'] = $row['CLID'];
    $row_array['tokens'] = "";
    $results[] = $row_array;
}

$json = json_encode($results);
echo $json;
return $json;

令牌行进入数组很好但是我不确定如何格式化它,我知道它需要采用以下格式

tokens:[
"token1", "token2", "token3"
]

令牌将是 NAME 和 CLID 的值,我如何才能创建令牌以使其理想地看起来像这样:

{
name: "name",
CLID: "CLID",
tokens: [
"name1", "clid1", "name2", "clid2", "name3", "clid3"...
]
}
4

1 回答 1

0

Managed to figure it out by reading up some more, to create a nested json element you need to add in through an array within an arry

while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $row_array['NAME'] = $row['NAME'];
    $row_array['CLID'] = $row['CLID'];
    $row_array['tokens'] = array($row["NAME"],$row["CLID"]); //create new array and add the tokens you want
    $results[] = $row_array;
}
于 2013-11-21T16:14:33.107 回答