通过mysql从php创建json对象 [英] Create json Object by php from mysql result
问题描述
可能重复:
JSON编码MySQL结果
Possible Duplicate:
JSON encode MySQL results
我想使用php创建如下的json对象.它将返回一个字符串作为来自结果sql查询的响应.
I want to use php to create a json object like below. it will return a string as a response from result sql query.
{"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();
?>
但是当使用我的代码时,结果却不是我期望的:
But when use my code the result is not what I expected:
{订单":[ ["longvan","2012年10月12日","Be34433jh","Long Van","115 Pham Viet Chanh和quan Binh Thanh","http://longvansolution.tk/image/sample.jpg",包装","0909056788"], ["takeshi","2012/12/24","BF6464633","Vn-zoom","16 nguyen cuu van,quan binh thanh","http://longvansolution.tk/image/hoadon3.jpg", 已打包","098897657"] ]}
{"Orders":[ ["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://longvansolution.tk/image/hoadon3.jpg","PACKED","098897657"] ]}
你能帮我吗?
推荐答案
您必须为每行创建一个数组以指定字段名称和值.
You have to create an array for each row to specify the field name and value.
$json['Orders'][] = array('DeliveryId' => $row[0], 'CustomerName' => $row[1], ...);
或者如果表列名称正是您所使用的名称,则使用 mysqli_fetch_assoc()函数想要在您的JSON中使用:
Or use mysqli_fetch_assoc() function if the table column name is exactly what you want to use in your JSON:
$rows = array();
while($r = mysqli_fetch_assoc($sql)) {
$rows[] = $r;
}
$data = array('Orders' => $rows);
print json_encode($data);
这篇关于通过mysql从php创建json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!