我正在尝试从mysql动态创建一个json,使用我在这个线程中找到的这段代码使用php-mysql创建嵌套的json对象似乎相当容易。但是,我想在$json\u响应前后添加一些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":
最后这个代码
}
]
}
}
2条答案
按热度按时间ddarikpa1#
声明数组时
$json_response = array();
你可以用你的默认值来准备它uz75evzq2#
非常简单:
就我个人而言,我会重新命名
$json_response
至$messages
为了清楚起见。