将json代码附加到从mysql和php创建的json中

m1m5dgzv  于 2021-06-23  发布在  Mysql
关注(0)|答案(2)|浏览(359)

我正在尝试从mysql动态创建一个json,使用我在这个线程中找到的这段代码使用php-mysql创建嵌套的json对象似乎相当容易。但是,我想在$json\u响应前后添加一些json代码。
主代码

  1. $result = mysql_query("SELECT * FROM Places ");
  2. $json_response = array(); //Create an array
  3. while ($row = mysql_fetch_array($result))
  4. {
  5. $row_array = array();
  6. $row_array['title'] = $row['title'];
  7. $row_array['image_url'] = $row['image_url'];
  8. $row_array['subtitle'] = $row['subtitle'];
  9. $row_array['buttons'] = array();
  10. $id = $row['id'];
  11. $option_qry = mysql_query("SELECT * FROM Places where id=$id");
  12. while ($opt_fet = mysql_fetch_array($option_qry))
  13. {
  14. $row_array['buttons'][] = array(
  15. 'type' => $opt_fet['type'],
  16. 'caption' => $opt_fet['caption'],
  17. 'url' => $opt_fet['url'],
  18. );
  19. }
  20. array_push($json_response, $row_array); //push the values in the array
  21. }
  22. echo json_encode($json_response, JSON_PRETTY_PRINT);

生成此json

  1. [
  2. {
  3. "title": "Name of the place",
  4. "image_url": "image.jpg",
  5. "subtitle":Additional info",
  6. "buttons": [
  7. {
  8. "type": "'url'",
  9. "caption": "More Info",
  10. "url": "https://some link "
  11. }
  12. ]
  13. },
  14. {
  15. "title": "Name of the place 2",
  16. "image_url": "image2.jpg",
  17. "subtitle":Additional info2",
  18. "buttons": [
  19. {
  20. "type": "'url'",
  21. "caption": "More Info",
  22. "url": "https://some link 2"
  23. }
  24. ]
  25. }
  26. ]

我不得不在已经创建的json之前添加以下代码

  1. {
  2. "version": "v2",
  3. "content": {
  4. "messages": [
  5. {
  6. "type": "cards",
  7. "elements":

最后这个代码

  1. }
  2. ]
  3. }
  4. }
ddarikpa

ddarikpa1#

声明数组时 $json_response = array(); 你可以用你的默认值来准备它

  1. $stdObj=new \stdClass();
  2. $stdObj->version="V2";
  3. $stdObj->content=(object)["messages"=>(object)["type"=>'cards','elements'=>$row_array['buttons']]];
  4. echo json_encode($stdObj, JSON_PRETTY_PRINT);
uz75evzq

uz75evzq2#

非常简单:

  1. $final_json = [
  2. "version" => "v2",
  3. "content" => [
  4. "messages" => [[
  5. "type" => "cards",
  6. "elements" => $json_response
  7. ]]
  8. ]
  9. ];
  10. echo json_encode($final_json, JSON_PRETTY_PRINT);

就我个人而言,我会重新命名 $json_response$messages 为了清楚起见。

相关问题