[英]Format Array Data to JSON_ENCODE using php
我正在使用php将数组数据格式化为Json_encode
。 该数组数据来自我的数据库。 我已经描述了我如何在这里做
$pens=$db->fetchAllPens(); //This fetches the list of pens
$a = array();
$response = array();
$response["success"]="true";
while ($pen = mysqli_fetch_array($pens)) {
$response["label"]["id"]=$pen["ID"];
$response["label"]["name"] = $pen["name"];
array_push($a,$response);
}
echo json_encode($a,JSON_PRETTY_PRINT);
上面的代码给了我下面的输出
[
{
"success": "true",
"label": {
"id": "1",
"name": "nimble"
}
},
{
"success": "true",
"label": {
"id": "2",
"name": "lopsel"
}
}
]
但是我期望下面的输出
{
"success":true,
"label":[
{
"id":1,
"name":"nimble"
},
{
"id":2,
"name":"lopsel"
}
]
}
请有一种方法来达到预期的效果。
$pens = $db->fetchAllPens(); //This fetches the list of pens
$response = array('success' => true, 'label' => array());
while ($pen = mysqli_fetch_array($pens)) {
$response['label'][] = array('id' => $pen['ID'],
'name' => $pen['name']
);
}
echo json_encode($response,JSON_PRETTY_PRINT);
在每个循环周期中,您正在写入错误的变量。
而是执行以下操作:
while ($pen = mysqli_fetch_array($pens)) {
$data[] = [
'id' => $pen['ID'],
'name' => $pen['Name'],
];
}
$response['label'] = $data;
echo json_encode($response,JSON_PRETTY_PRINT);
首先将status
直接放入$a
数组中。
然后将行数据放入$a['label'][]
即$a['label']
数组的新出现
$pens=$db->fetchAllPens(); //This fetches the list of pens
$a = array();
$a["success"] = "true";
while ($pen = mysqli_fetch_array($pens)) {
$response = array();
$response["id"] = $pen["ID"];
$response["name"] = $pen["name"];
$a['label'][] = $response;
}
echo json_encode($a,JSON_PRETTY_PRINT);
结果:
{
"success": "true",
"label": [
{
"id": 1,
"name": "fred"
},
{
"id": 2,
"name": "Bill"
}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.