我的 php 代码如下:
$query = "SELECT *
FROM `address`
WHERE customer_id =$customer_id
ORDER BY `default` DESC";
$result=mysql_query($query);
$value = mysql_num_rows($result);
if($value>=1)
{
while($row = mysql_fetch_array($result))
{
$details = array(
'status'=>'sucess',
'message'=>'address available',
'id' => $row['id'],
'customer_id' =>$row['customer_id'],
'at' => $row['at'],
'name'=>$row['name'],
'mobile'=>$row['mobile'],
'city'=>$row['city'],
'address'=>$row['address'],
'latlog'=>$row['latlog'],
'default'=>$row['default']
);
}
echo json_encode($details);
}
它的输出看起来像:
{"status":"sucess","message":"address available","id":"52","customer_id":"14","at":"Home","name":"Shhsh","mobile":"99989998","city":"Calicut","address":"Gsggsgs","latlog":"76.3007429,76.3007429","default":"Yes"}
它是 json 对象。我需要的 json 是:
{"status":"sucess","message":"address available","details":[{"id":"52","customer_id":"14","at":"Home","name":"Shhsh","mobile":"99989998","city":"Calicut","address":"Gsggsgs","latlog":"76.3007429,76.3007429","default":"Yes"}]
}
我应该对所需的 json 格式进行哪些更改?即 json 对象包含 json 数组。为了获得所需的 json 格式,我应该做哪些更改。我是新来的。提前致谢。
最佳答案
您需要在外部创建一个数组来附加结果数据,然后在将其解码为 JSON 之前将其放入主数组中。
像这样,
if($value>=1)
{
$details=array();
while($row = mysql_fetch_array($result))
{
$details[]= array(
'id' => $row['id'],
'customer_id' =>$row['customer_id'],
'at' => $row['at'],
'name'=>$row['name'],
'mobile'=>$row['mobile'],
'city'=>$row['city'],
'address'=>$row['address'],
'latlog'=>$row['latlog'],
'default'=>$row['default']
);
}
$main_array=array();
$main_array['status']='sucess';
$main_array['message']='address available';
$main_array['details']=$details;
echo json_encode($main_array);
}
这将生成这样的 JSON,http://json-parser.com/deec3edd
关于php - 如何显示Mysql php结果json格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39245237/