我想用php创建一个像下面这样的json。它将返回一个字符串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”,“压缩”, “0909056788”], [“takehi”,“24/12/2012”,“BF6464633”,“Vn-zoom”,“16 nguyen cuu van,quan binh thanh”,“http://longvansolution.tk/image/hoadon3.jpg”, “压缩”, “098897657”] ]} 你能帮助我吗!
答案 0 :(得分:1)
您可以使用json_encode()功能来执行此操作。
您的JSON格式无效。使用:
代替=
答案 1 :(得分:0)
// SERVER SIDE
<?php
//... create array
//....Obviously you would use your own SQL link and query
$animals = array();
$result = @mysqli_query('YOUR DB LINK', 'YOUR QUERY');
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
array_push($animals, array(
'animal' => $row['animal'],
'sound' => $row['sound']
));
}
?>
// CLIENT SIDE
<html>
<script>
// RETURN FROM PHP PAGE ECHO VIA AJAX PERHAPS //
var animals = <?php echo json_encode($animals) ?>;
$.each(animals, function (i, elem) {
console.log(elem.animal + " makes a " + elem.sound);
});
</script>
</html>