开发者

how do i format my JSON responce in PHP to look like this

开发者 https://www.devze.com 2023-02-05 03:49 出处:网络
My PHP code: require (\"connect.php\"); $input = $_GET[\"query\"]; $data = array(); $query = mysql_query(\"SELECT `abbr` FROM `states_list` WHERE `abbr` LI开发者_高级运维KE \'{$input}%\'\") or die(

My PHP code:

require ("connect.php");

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

$query = mysql_query("SELECT `abbr` FROM `states_list` WHERE `abbr` LI开发者_高级运维KE '{$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).'}';

This is my actual response:

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

This is how I would like it to look like:

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

I can't seem to figure out the right way to arrange the output to get what I want ;(


Try changing your $json[] = $obj; to $json[] = $obj->abbr;.


Try formatting it like this:

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

Build $query and $suggestion in the loops.


I'd rewrite it to this- the while loop creates an array consisting of suggestions, then it is encoded.

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. Also, don't forget to properly escape the string taken from user input in order to avoid sql injections.

0

精彩评论

暂无评论...
验证码 换一张
取 消