如何在PHP中以适当的JSON格式输出?

时间:2017-04-09 12:11:02

标签: php arrays json

我想通过以下方式在resCode中使用resTextJSON从mysql表中输出一些记录:

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

由于我对PHP数组很新,我无法将服务器端部分格式化为输出,如上所述。此外,我不知道如何输出resCode和resText。

对此相同的任何帮助将不胜感激。

PHP部分:

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

2 个答案:

答案 0 :(得分:1)

试试这个

 $stmt->bind_result($id, $month, $income, $expanse);
    $response = array();
    $data = array();
    while ($stmt->fetch()) {
        $data[]=array(id=>$id, month=>$month, income=>$income,expanse=>$expanse);
    }
       $response["data"] = $data;
       $response["resCode"] = "XXX";
       echo json_encode($response);

答案 1 :(得分:1)

while ($stmt->fetch()) {
    $output["data"][]=array('id'=>$id, 'month'=>$month, 'income'=>$income, 'expanse'=>$expanse);        
}
$output["resCode"] = '200';
$output["resText"] = 'SUCCESS';
echo json_encode($output);