我想在从 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
}
]
}
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)
从 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"
}
Run Code Online (Sandbox Code Playgroud)
根据预期的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);
Run Code Online (Sandbox Code Playgroud)