Skip to content
Advertisement

How do I output in proper JSON format in PHP?

I want to output some records from mysql table with resCode and resText in JSON in the following way:

{  
   "data":[  
             {  
                "id":"44",
                "month":"January",
                "income":"2500",
                "expanse":"0"
             },
             {  
                "id":"45",
                "month":"February",
                "income":"5500",
                "expanse":"400"
             },
             {  
                "id":"47",
                "month":"March",
                "income":"25000",
                "expanse":"11000"
             }
        ],
   "resCode":"200",
   "resText":"SUCCESS"
}

Since I’m very new to PHP arrays, I’m unable to format the server side part to output like above. Also I don’t know how to output the resCode and resText.

Any help for the same will be appreciated.

PHP part:

<?php
include_once 'includes/db_connect.php';
?>

<?php
$stmt = $mysqli->prepare("SELECT * FROM records");
        $stmt->execute();    // Execute the prepared query.
        $stmt->store_result();

        // get variables from result.
        $stmt->bind_result($id, $month, $income, $expanse);
        while ($stmt->fetch()) {
            $data[]=array(id=>$id, month=>$month, income=>$income, expanse=>$expanse);
        }
            $response["data"] = $data;
            $response["resCode"] = "200";

            echo json_encode($response);
?>

Advertisement

Answer

while ($stmt->fetch()) {
    $output["data"][]=array('id'=>$id, 'month'=>$month, 'income'=>$income, 'expanse'=>$expanse);        
}
$output["resCode"] = '200';
$output["resText"] = 'SUCCESS';
echo json_encode($output);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement