我使用的是examplep,即使我在表中将id列设置为整数,输出仍然是字符串,即我得到的是"id":"1"
而不是"id":1
。我通过JSON_NUMERIC_CHECK
找到了一个可能的解决方案,但我不知道如何在我的php脚本中实现它。有人能告诉我如何修改我的php脚本,以便将id输出为整数吗。
<?php
require("config.inc.php");
$query_params=null;
$query = "Select * FROM feeds";
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if ($rows) {
$response["feed"] = array();
foreach ($rows as $row) {
$post = array();
$post["id"] = $row["id"];
$post["name"] = $row["name"];
$post["image"] = $row["image"];
array_push($response["feed"], $post);
}
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Post Available!";
die(json_encode($response));
}
?>
只需将选项添加到json_encode()
调用-
json_encode( $response, JSON_NUMERIC_CHECK );
json_encode()
无论PHP说值的类型是什么都会熄灭:
php > $arr = array('id' => '1');
php > var_dump($arr);
array(1) {
["id"]=>
string(1) "1"
}
php > echo json_encode($arr);
{"id":"1"}
由于1
是PHP中的字符串,因此它也将是JSON中的字符串。所以强制它为int:
php > $arr = array('id' => (int)'1');
^^^^^-----note the typecast here.
php > var_dump($arr);
array(1) {
["id"]=>
int(1)
}
php > echo json_encode($arr);
{"id":1}