我想在从mySQL派生的数据之前添加一些字符串。并以JSON
输出它们.我可以根据自己的需要从mySQL中提取数据。但是我无法将前缀字符串添加到正确的格式。
预期的 json 格式
{
"message": "",//i can do this
"value": [//but I can't do this the "value":[
{
"excName": "Mark",
"excSup": "chunyun",
"excId": 20001
}, {
"excName": "orion-01",
"excSup": "orion-01",
"excId": 20000
}
]
}
.PHP
while ($rec_qXcur=mysqli_fetch_assoc($sql_qXcur)){
$data[] = array(
"excId"=>$rec_qXcur['exc_id'],
"excTitle"=>$rec_qXcur['exc_name'],
"excSup"=>$rec_qXcur['exc_sup']
);
}
//return json data
echo json_encode($data);
从PHP我得到这个:
{
"message":"",
//"value":[//this is missing
"0":{//not need
"excId":"234",
"excTitle":"Simon Cabaret - Regular Seat ",
"excSup":"simon"
},
"1":{//not need
"excId":"245",
"excTitle":"Simon Cabaret - VIP Seat (01Nov15 - 30Apr16)",
"excSup":"simon"
}
根据预期的 json 格式。我错过了"value":[
.我尝试将其添加到$data
但它不起作用。
你只是把它们添加到数据中。您需要将它们添加到value
数组中。
因此,json_encode()
可能正在创建一个对象文字{}
因为您的数组同时具有命名元素和顺序元素。一旦它只包含顺序元素,json_encode()
应该(我相信)返回一个数组文字[]
;
$data = array(
'message' => 'Your message here',
'value' => array()
);
while ($rec_qXcur=mysqli_fetch_assoc($sql_qXcur)){
$data['value'][] = array(
"excId"=>$rec_qXcur['exc_id'],
"excTitle"=>$rec_qXcur['exc_name'],
"excSup"=>$rec_qXcur['exc_sup']
);
}
echo json_encode($data);