簡體   English   中英

格式化JSON以包含來自mysql和php的列表

[英]Format JSON to contain a list from mysql and php

我前一陣子問過,但沒有任何設置。 現在,我對需要做的事情有了更多的了解。

我有一個SQL查詢,返回以下結果:

1   Baked Apple Apple
2   Seafood Rice Balls  Hylian Rice
2   Seafood Rice Balls  Hyrule Bass

它是由存儲過程生成的,該存儲過程僅聯接了一個食物表,一個食物成分多表和成分表。

SELECT F.Id, F.Name 'Dish', I.Name 'Ingredient' FROM `Food` F
JOIN Food_Ingredients FI ON F.Id = FI.`FoodId`
JOIN Ingredients I ON FI.`IngredientsId` = I.Id;

通過PHP轉換為JSON時,將產生以下結果:

[
 {
  "Id": "1",
  "Dish": "Baked Apple",
  "Ingredient": "Apple"
 },
 {
   "Id": "2",
   "Dish": "Seafood Rice Balls",
   "Ingredient": "Hylian Rice"
 },
 {
   "Id": "2",
   "Dish": "Seafood Rice Balls",
   "Ingredient": "Hyrule Bass"
 }
]

我需要以某種方式將其轉換為以下格式:

[
 {
  "Id": "1",
  "Dish": "Baked Apple",
  "Ingredients": [
    {
     "Name": "Apple",
     "Id": "1"
    }
  ]
 },
 {
  "Id": "2",
  "Dish": "Seafood Rice Balls",
  "Ingredients": [
  {
   "Name": "Hylian Rice",
   "Id": 5
  },
  {
   "Name": "Hyrule Bass",
   "Id": 6
  }
  ]
 }
]

我也只想真正擁有1個查詢,因為這可能會變得很大,而且我覺得運行許多查詢會很慢

如果第二個JSON的語法不正確,我也要手動輸入

這是我正在使用的PHP代碼: PHP代碼

$sql = 'CALL GetAllDishIngredients()';
$data = mysqli_query($db, $sql);
$cnt = mysqli_num_rows($data);

$results = array();

while($row = mysqli_fetch_array($data)){
    $id = $row['Id'];
    $dishname = $row['Dish'];
    $ing = array();

    $ing[] = array(
        'Id' => $row['iId'],
        'IngredientName' => $row['Ingredient']
    );

    if(!isset($results[$id]))
    {
        $results[$id] = array(
          'Id' => $row['Id'],
          'Dish' => $row['Dish'],
          'Ingredients' => $ing
       );
    }
    else{
        array_push($results[$id]['Ingredients'], $ing[0]);
    }
}
$json = json_encode($results, JSON_PRETTY_PRINT);

那就是我最終做的方式。 我使用isset變量檢查ID是否已存在於數組中。 如果是這樣,我使用array_push將成分添加到數組中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM