让我首先开始,抱歉标题令人困惑。我不知道如何准确地描述它,但这里是。所以我在数据库中查询字符串。如果只找到 1 个结果,那么创建一个数组、用信息填充它、编码 JSON 并返回它相对容易。我对何时有多个结果感到困惑。下面的代码是我正在使用的,但我非常怀疑它是否正确。我无法使用我需要的方法将其编码为 JSON 格式。如果您至少可以帮助我指出正确的方向,我将不胜感激!谢谢!
PHP:
if ($action == 'profile') {
while ($pson = mysql_fetch_array($personQuery)) {
$typeSearch = 'profile';
$profQuery = mysql_query("SELECT * FROM tableName WHERE ColumnName LIKE '$query'");
$compQuery = mysql_query("SELECT * FROM tableName2 WHERE ColumnName LIKE '$query'");
if ($profQuery && mysql_num_rows($profQuery) > 0) {
$personQueryRows = mysql_num_rows($profQuery);
while ($row = mysql_fetch_array($profQuery)) {
if ($compQuery && mysql_num_rows($compQuery) > 0) {
while ($com = mysql_fetch_array($compQuery)) {
if (mysql_num_rows($profQuery) > 1) {
$compQueryRows = mysql_num_rows($compQuery);
if ($compQueryRows > 0) {
$compReturn = "true";
} else {
$compReturn = "false";
}
$nameArray = Array(
"success"=>"true",
"date"=>date(),
"time"=>$time,
"action"=>$action,
"returned"=>"true"
);
global $result;
for ($i=1;$i<=$personQueryRows;$i++) {
$nameResult[$i]=Array(
"id"=>$row['id'],
"name"=>$row['name'],
"gender"=>$row['gender'],
"comp"=>$row['company'],
"queryType"=>"profile"
);
$result = array_merge($nameArray, $nameResult[$i]);
}
$encodedJSON = json_encode($result);
echo $encodedJSON;
}
}
}
}
}
}
}
}
返回的 JSON:
{"success":"true","date":"Jun 29 2012","time":"14:43:16","action":"profile","returned":"true","id":"14321","name":"John Smith","gender":"male","comp":"ABC Studios, LLC.","queryType":"profile"}
{"success":"true","date":"Jun 29 2012","time":"14:43:16","action":"profile","returned":"true","id":"292742","name":"John Smith","gender":"male","comp":"DEF Studios, LLC.","queryType":"profile"}
JavaScript 错误(解析 JSON 时):
Uncaught SyntaxError: Unexpected token {
PS 我刚刚开始使用 PHP 数组和 JSON 格式,所以如果这完全错误,我深表歉意。还在学习阶段。