将 JSON 字符串转换为整数(integer)在 PHP 中

3
我正在使用xampp,尽管我在表中将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));
    }

?>

1
如果您使用的是PHP 5.3.3,则只需使用json_encode($response, JSON_NUMERIC_CHECK); - AbraCadaver
你需要使用(int)进行类型转换。 - floor
2个回答

8
只需在 json_encode() 调用中添加选项 -
json_encode( $response, JSON_NUMERIC_CHECK );

3

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"}

由于在PHP中,您的1是一个字符串,因此在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}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接