我如何在PHP中格式化我的JSON响应看起来像这样

时间:2011-01-18 20:40:59

标签: php json

我的PHP代码:

require ("connect.php");

$input = $_GET["query"];
$data = array();

$query = mysql_query("SELECT `abbr` FROM `states_list` WHERE `abbr` LIKE '{$input}%'") or die(mysql_error());
while ($obj = mysql_fetch_object($query)) {
    //$json = array();
    //$json['query'] = $input;
    //$json['suggestion'] = $row['abbr'];
    $json[] = $obj;
    $data = array("query"=>"$input", "suggestion"=>array($obj));
}
header("Content-type: application/json");
//echo json_encode($data);
echo '{"query":'.$input.' "suggestion":'.json_encode($json).'}';

这是我的实际回应:

{"query":c "suggestion":[{"abbr":"CA"},{"abbr":"CO"},{"abbr":"CT"}]}

这就是我希望它的样子:

{"query":c "suggestion":["CA","CO","CT"]}

我似乎无法找到正确的方法来安排输出以获得我想要的东西;(

3 个答案:

答案 0 :(得分:2)

尝试将$json[] = $obj;更改为$json[] = $obj->abbr;

答案 1 :(得分:1)

尝试将其格式化为:

$query = "c";
$suggestion = array('CA', 'CO', 'CT');
$return = array('query' => $query, 'suggestion' => $suggestion);
echo json_encode($return);

在循环中构建$query$suggestion

答案 2 :(得分:0)

我将其改写为此 - while循环创建一个由建议组成的数组,然后对其进行编码。

require ("connect.php");

$input = mysql_real_escape_string($_GET["query"]);
$data = array();

$query = mysql_query("SELECT `abbr` FROM `states_list` WHERE `abbr` LIKE '{$input}%'") or die(mysql_error());
while ($obj = mysql_fetch_object($query)) {
    $data[] = $obj->abbr;
}
header("Content-type: application/json");
echo '{"query":'.$input.' "suggestion":'.json_encode($data).'}';

P.S。另外,不要忘记正确转义从用户输入中获取的字符串,以避免sql注入。