2012-12-19 24 views
3

可能重复:
JSON encode MySQL results通过PHP从MySQL结果创建JSON对象

我想用PHP创建一个JSON对象,像下面。它将返回一个字符串作为结果sql查询的响应。

{"Orders":[ 
      {"DeliveryId":"DeliveryId","CustomerName":"CustomerName","PhoneNumber":"PhoneNumber","Address":"Address"}, 
      {"DeliveryId":"DeliveryId","CustomerName":"CustomerName","PhoneNumber":"PhoneNumber","Address":"Address"}    
] 
} 

我的代码

<?php 
mysql_connect("mysql12.000webhost.com","a4602996_longvan","longvan2012"); 
mysql_select_db("a4602996_lv"); 
$id=$_POST[user]; 
$sql=mysql_query("select * from testlongvan where Status = 'PACKED'"); 

$json = array(); 
if(mysql_num_rows($sql)){ 
while($row=mysql_fetch_row($sql)){ 
$json['Orders'][]=$row; 
} 
} 

//while($row=mysql_fetch_assoc($sql)) 
//$output[]=$row; 
print(json_encode($json)); 
mysql_close(); 
?> 

但是,当使用我的代码的结果不是我所期待的:

{ “订单”: [ “longvan”,“10/12/2012“,”Be34433jh“,”Long Van“,”115 Pham Viet Chanh,quan Binh Thanh“,”http://longvansolution.tk/image/sample.jpg“,”PACKED“,”0909056788“], [“takeshi”,“24/12/2012”,“BF6464633”,“Vn-zoom”,“16 nguyen cuu van,quan binh thanh”,“http:// long vansolution.tk/image/hoadon3.jpg","PACKED","098897657" ] ]}

你能帮助我吗?

+0

有一个在关于字符串类型的问题匹配的问题+答案:HTTP ://stackoverflow.com/questions/28261613/convert-mysql-result-to-json-with-correct-types –

+0

删除您的托管密码 –

回答

12

您必须为每行创建一个数组来指定字段名称和值。

$json['Orders'][] = array('DeliveryId' => $row[0], 'CustomerName' => $row[1], ...); 

或者使用mysqli_fetch_assoc()功能如果表列名是你想在你的JSON使用什么:

$rows = array(); 
while($r = mysqli_fetch_assoc($sql)) { 
    $rows[] = $r; 
} 
$data = array('Orders' => $rows); 
print json_encode($data); 
+0

有谁知道如何从每行$行的结果中获得一行中的所有列?没有指定每个列名? – jamis0n

+0

使用[mysql_fetch_assoc()](http://php.net/manual/en/function.mysql-fetch-assoc.php)函数 – Stanley

+3

**否**,使用[mysql *** i *** _fetch_assoc( )](http://php.net/manual/en/mysqli-result.fetch-assoc.php) – dualed