简体   繁体   中英

Format JSON to contain a list from mysql and php

I asked this a while ago but I didn't have anything set up. Now I have more of a grasp on what I need to do.

I have an SQL query that returns the following result:

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

Which is generated from a stored procedure that just joins a food table, a food-ingredient many-many table, and the ingredients table.

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;

When converted into JSON via PHP, it produces the following result:

[
 {
  "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"
 }
]

I need to somehow get it into this format:

[
 {
  "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
  }
  ]
 }
]

I'd also like to only really have 1 query, as this may get very large and I feel like running many queries is going to be slow

Also sorry if the syntax for the second JSON is incorrect, I manually typed that one in

Here's the PHP code I'm using: 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);

That's how I ended up doing it. I used the isset variable to check to see if the Id already exists in the array. If it does, I use array_push to add the ingredient to the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM