3

I'm using xampp and even though I've set the id column as integer in my table, the output is still string i.e I get "id":"1" instead of "id":1. I've come across a possible solution via JSON_NUMERIC_CHECK but I don't know how to implement this in my php script. Can someone show me how to modify my php script in order to have the id output as an integer.

    <?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));
    }

?>
2
  • 1
    If you have PHP 5.3.3 then just json_encode($response, JSON_NUMERIC_CHECK); Commented Feb 23, 2015 at 21:06
  • you need to type cast it using (int) Commented Feb 23, 2015 at 21:08

2 Answers 2

8

Just add the option to the json_encode() call -

json_encode( $response, JSON_NUMERIC_CHECK );
Sign up to request clarification or add additional context in comments.

Comments

3

json_encode() goes off whatever PHP says the value's type is:

php > $arr = array('id' => '1');
php > var_dump($arr);
array(1) {
  ["id"]=>
  string(1) "1"
}
php > echo json_encode($arr);
{"id":"1"}

Since your 1 is a string in PHP, it'll be a string in JSON as well. So force it to be an 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}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.