php - 将 JSON 代码附加到从 MySQL 和 PHP 创建的 JSON
问题描述
我正在尝试从 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":
最后这段代码
}
]
}
}
解决方案
很简单:
$final_json = [
"version" => "v2",
"content" => [
"messages" => [[
"type" => "cards",
"elements" => $json_response
]]
]
];
echo json_encode($final_json, JSON_PRETTY_PRINT);
就个人而言,为了清楚起见,我会重命名$json_response
为。$messages
推荐阅读
- python - 规范化在我的数据框中引入了一些 NaN
- wpf - 控件模板中的 WPF 命令 - >“CommandConverter 无法从 > System.String 转换。”
- python-3.x - 类型错误:“dict”对象不可调用
- c# - 使用 Blazor 服务器端
- flutter - 扑。路径缩放
- php - 使用php从二进制输入中解析字节字符串
- ios - 在 SwiftUI 中单击 NavigationView 的后退按钮时更新核心数据
- postgresql - Postgres为带有时区的时间戳插入数据
- java - aks 上的 java spingboot 微服务部署抛出 UnsupportedClassVersionError
- react-native - React native TouchableOpacity onPress 在 Android Build (APK) 上不起作用