我正在尝试从MySQL动态创建JSON,对于在线程Create nested json object using php mysql中找到的这段代码,这似乎相当容易。 但是,我想在$ json_response之前和之后添加一些JSON代码。
主要代码
$result = mysql_query("SELECT * FROM Places ");
$json_response = array(); //Create an array
while ($row = mysql_fetch_array($result))
{
$row_array = array();
$row_array['title'] = $row['title'];
$row_array['image_url'] = $row['image_url'];
$row_array['subtitle'] = $row['subtitle'];
$row_array['buttons'] = array();
$id = $row['id'];
$option_qry = mysql_query("SELECT * FROM Places where id=$id");
while ($opt_fet = mysql_fetch_array($option_qry))
{
$row_array['buttons'][] = array(
'type' => $opt_fet['type'],
'caption' => $opt_fet['caption'],
'url' => $opt_fet['url'],
);
}
array_push($json_response, $row_array); //push the values in the array
}
echo json_encode($json_response, JSON_PRETTY_PRINT);
产生此JSON
[
{
"title": "Name of the place",
"image_url": "image.jpg",
"subtitle":Additional info",
"buttons": [
{
"type": "'url'",
"caption": "More Info",
"url": "https://some link "
}
]
},
{
"title": "Name of the place 2",
"image_url": "image2.jpg",
"subtitle":Additional info2",
"buttons": [
{
"type": "'url'",
"caption": "More Info",
"url": "https://some link 2"
}
]
}
]
我有某种方法可以在已创建的JSON之前添加以下代码
{
"version": "v2",
"content": {
"messages": [
{
"type": "cards",
"elements":
最后这段代码
}
]
}
}
答案 0 :(得分:3)
非常简单:
$final_json = [
"version" => "v2",
"content" => [
"messages" => [[
"type" => "cards",
"elements" => $json_response
]]
]
];
echo json_encode($final_json, JSON_PRETTY_PRINT);
为清晰起见,我个人将$json_response
重命名为$messages
。
答案 1 :(得分:1)
在声明数组$json_response = array();
的同时,您实际上可以使用默认值require来准备它
$stdObj=new \stdClass();
$stdObj->version="V2";
$stdObj->content=(object)["messages"=>(object)["type"=>'cards','elements'=>$row_array['buttons']]];
echo json_encode($stdObj, JSON_PRETTY_PRINT);