【问题标题】:Get all drinks from database with their ingredients in json fromat - PHP - mySQL从数据库中获取所有饮料及其成分为 json 格式 - PHP - mySQL
【发布时间】:2018-06-20 12:49:04
【问题描述】:

我用 mySQL 创建了一个简单的数据库:

  1. 餐桌 - 饮品:id、姓名、...

  2. 表格 - 成分:id、名称、...

  3. 表格 - Drink_Ingredients:drink_id,component_id

我想查询并得到如下格式的json:

[{
  "id": "000a1",
  "name": "Mojito",
  "ingredients": [{
      "id": "000i1",
      "name": "Lime"
  }, {
      "id": "000i2",
      "name": "Bacardi"
  }]

 }, {
  "id": "000d2",
  "name": "Cuba Libre",
  "ingredients": [{
      "id": "000i3",
      "name": "Rum"
  }, {
      "id": "000i4",
      "name": "Cola"
  }]

}]

我怎样才能做到这一点?我是否应该先请求获取所有饮料,然后遍历所有饮料并在内部提出另一个请求以获取其成分?我还需要相应的 PHP 对象来处理数据然后打印 JSON 还是没关系?

【问题讨论】:

  • “我是否应该先请求获取所有饮料,然后遍历所有饮料并在内部发出另一个请求以获取其成分?我还需要相应的 PHP 对象来处理数据吗?然后打印 JSON" ...是和否。
  • 你可以写一个Join查询来实现这个结果集

标签: php mysql sql json


【解决方案1】:

首先得到你需要的数据:

$drinks = array();
$i = 0;
$sql = "SELECT id,name FROM drinks";
//conn is your database connect variable
$result = $conn->query($sql);
foreach($result as $v=>$row){
   $drinks[$i]['name'] = $row["name"];
   $drinks[$i]['id'] = $row["id"];
   $drinks[$i]['ingredients'] = array();
   $j = 0;
   $sql2 = "SELECT ingredients_id, name FROM drink_Ingredients INNER JOIN ingredients on drink_Ingredients.ingredients_id=ingredients.id";
   $result2 = $conn->query($sql2);
   foreach($result2 as $v2=>$row2){
       $drinks[$i]['ingredients'][$j]['id'] = $row2["ingredients_id"];
       $drinks[$i]['ingredients'][$j]['name'] = $row2["name"];
       $j++;
   }
   $i++
}

拥有drinks数组后,你需要制作json:

$json = json_encode($drinks);

就是这样:)

【讨论】:

  • 效果很好!你为我节省了很多时间。谢谢罗伯特!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 2016-06-05
  • 2015-05-14
  • 2021-10-03
  • 1970-01-01
  • 2021-11-08
相关资源
最近更新 更多