Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert json string to integer in php

Tags:

string

php

int

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

?>
like image 307
Macharia Avatar asked Sep 13 '26 00:09

Macharia


1 Answers

Just add the option to the json_encode() call -

json_encode( $response, JSON_NUMERIC_CHECK );
like image 159
Jay Blanchard Avatar answered Sep 15 '26 15:09

Jay Blanchard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!