2017-04-09 69 views
0

我要输出的MySQL表通过以下方式的一些记录与resCoderesTextJSON如何在PHP中以正确的JSON格式输出?

{ 
    "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); 
?> 
+0

也请包括你的代码目前输出 –

+0

@SamiKuhmonen提示错误。至于我告诉你,我不不知道输出的正确方法。 –

回答

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); 
+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); 
+0

它显示了输出,但也显示错误:使用未定义的常量id - 在第13行E:\ wamp \ www \ admin \ json.php中假定'id'。还显示月份,收入和扩展为未定义常量 –

+0

opps 尝试这一个 $ data [] = array(“id”=> $ id,“month”=> $ month,“income”=> $ income,“expanse”=> $ expanse); –

+0

它的工作!谢谢。 –