【问题标题】:Convert json string to integer in php在php中将json字符串转换为整数
【发布时间】:2015-02-23 21:03:02
【问题描述】:

我正在使用 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));
    }

?>

【问题讨论】:

  • 如果你有 PHP 5.3.3 那么只需json_encode($response, JSON_NUMERIC_CHECK);
  • 您需要使用 (int) 进行类型转换

标签: php string int


【解决方案1】:

只需将选项添加到json_encode() 调用 -

json_encode( $response, JSON_NUMERIC_CHECK );

【讨论】:

    【解决方案2】:

    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}
    

    【讨论】:

      猜你喜欢
      • 2010-11-05
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-31
      相关资源
      最近更新 更多