php - 将 JSON 代码附加到从 MySQL 和 PHP 创建的 JSON

标签 php mysql 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

关于php - 将 JSON 代码附加到从 MySQL 和 PHP 创建的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51739815/

相关文章:

javascript - 如何验证股市数据

mysql - 定期更新MySQL数据库如何与网站分开

Javascript - 循环显示一些未定义的数组

php - 如何在 MySQL 语句中包含 PHP 变量

javascript - jQuery 序列化时出现 Safari JSON 错误

php - 使用插入查询 CI PHP Mysql Ajax

javascript - 如何使用 PHP 将数据保存在我的数据库中

php页面无法加载MySQL的数据库

php - 为什么我在 Shopware 中更新客户属性时收到无效参数错误?

javascript - <node.js> 如何有效地将平面值数组解析为具有嵌套属性的对象?