【问题标题】:Create json Object by php from mysql result [duplicate]通过php从mysql结果创建json对象[重复]
【发布时间】:2012-12-06 08:57:50
【问题描述】:

可能重复:
JSON encode MySQL results

我想使用 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","包装","0909056788"], ["takeshi","24/12/2012","BF6464633","Vn-zoom","16 nguyen cuu van, quan binh thanh","http://longvansolution.tk/image/hoadon3.jpg", "打包","098897657"] ]}

你能帮帮我吗?

【问题讨论】:

标签: php json


【解决方案1】:

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

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

如果表列名称正是您想要在 JSON 中使用的名称,则使用 mysqli_fetch_assoc() 函数:

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

【讨论】:

  • 有谁知道如何从每个 $row 结果中获取一行中的所有列?不指定每个列名?
  • 使用mysql_fetch_assoc()函数
  • 谢谢@dualed。我已经更新了答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-14
  • 2013-12-21
  • 1970-01-01
  • 2014-05-15
  • 2015-08-11
  • 2017-04-20
相关资源
最近更新 更多