将php转换为json文件的难度

时间:2016-11-15 04:07:57

标签: php android json database

我一直很厌烦将PHP转换为JSON文件,但生成的JSON文件与通常发生的情况非常不同。 该表格如下所示

 rid    rname     mobile       email          address     opentiming       closetiming    menuid       type     averagecost         image
  1     abc     9876543212 sbjaca@gmail.com  fdsjdsfdnm    00:10:00          00:00:00        1         asian       120         http://gjsblog.esy.es/images/download.png
  2    abcdefc  9876543212  ajit@gmail.com    qwertym      00:00:03          00:00:04        2        chinese      120         http://gjsblog.esy.es/images/The_Table.png

php文件出现在

下面
 //retrieve.php
<?php
include("dbconfig.php");
$result = @mysql_query("select * from Restaurants ");   

$response =array();

if(@mysql_num_rows($result)>0){

    $response['Restaurants'] = array();

    while($row=@mysql_fetch_array($result)){
        array_push($response['Restaurants'], $row);
    }
}

 if($result){
    $response['success']=1;
    $response['message']="Records Retrieved sucessfully";
 }else{
    $response['success']=0;
    $response['message']="Retrieval Failure";
 }

 echo json_encode($response);

?>

JSON包含列中的数据两次,一次在列名之前,一次在列名之后。 JSON显示为

{
  "Restaurants": [
    {
      "0": "1",
      "rid": "1",
      "1": "abc",
      "rname": "abc",
      "2": "9876543212",
      "mobile": "9876543212",
      "3": "sbjaca@gmail.com",
      "email": "sbjaca@gmail.com",
      "4": "fdsjdsfdnm",
      "address": "fdsjdsfdnm",
      "5": "00:10:00",
      "opentiming": "00:10:00",
      "6": "00:00:00",
      "closetiming": "00:00:00",
      "7": "1",
      "menuid": "1",
      "8": "asian",
      "type": "asian",
      "9": "120",
      "averagecost": "120",
      "10": "http:\/\/gjsblog.esy.es\/images\/download.png",
      "image": "http:\/\/gjsblog.esy.es\/images\/download.png"
    },
    {
      "0": "2",
      "rid": "2",
      "1": "abcdefc",
      "rname": "abcdefc",
      "2": "9876543212",
      "mobile": "9876543212",
      "3": "sbjaca@gmail.com",
      "email": "sbjaca@gmail.com",
      "4": "fdsjdsfdnm",
      "address": "fdsjdsfdnm",
      "5": "00:00:03",
      "opentiming": "00:00:03",
      "6": "00:00:04",
      "closetiming": "00:00:04",
      "7": "2",
      "menuid": "2",
      "8": "chinese",
      "type": "chinese",
      "9": "120",
      "averagecost": "120",
      "10": "http:\/\/gjsblog.esy.es\/images\/The_Table_(restaurant)_logo.png",
      "image": "http:\/\/gjsblog.esy.es\/images\/The_Table_(restaurant)_logo.png"
    }
  ],
  "success": 1,
  "message": "Records Retrieved sucessfully"
}

1 个答案:

答案 0 :(得分:1)

更改

while($row=@mysql_fetch_array($result))

while($row=@mysql_fetch_array($result, MYSQL_ASSOC))

因为如果你只使用第一个语句,MYSQL_BOTH将被用作默认值,并使结果数组成为这样。

只是一个建议,你最好使用MySQLi或PDO_MySQL,因为在PHP 5.5.0中已经弃用了mysql_fetch_array并在PHP 7.0.0中删除了