简体   繁体   中英

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

My PHP code:

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).'}';

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).'}';

PS Also, don't forget to properly escape the string taken from user input in order to avoid sql injections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM