我最近开始在一个新项目中使用 twitter typeahead 插件,但遇到了一些障碍,我正在查询 1 个表中的 2 列以获取要搜索的数据,但是当我只搜索 1 列时,它工作正常当移动到两个时,我相信我需要开始使用 token 进行搜索。
但是我无法找到一种方法将 token 添加到我的数组中,然后将它们编码为 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;
token 行很好地进入数组,但是我不确定如何格式化它,我知道它需要采用
的格式tokens:[
"token1", "token2", "token3"
]
token 将是 NAME 和 CLID 的值,我如何创建 token 以理想地如下所示:
{
name: "name",
CLID: "CLID",
tokens: [
"name1", "clid1", "name2", "clid2", "name3", "clid3"...
]
}
最佳答案
通过阅读更多内容设法弄清楚,要创建一个嵌套的 json 元素,您需要通过 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;
}
关于php - 从 mysql 查询创建 token 列表到 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20121403/