Json输出SQL查询

时间:2016-11-02 17:15:25

标签: php json

SQl table

如何获取JSON中的输出,如下所示:

<div class="card_container">
  <div class="spinner"></div>
</div>

1 个答案:

答案 0 :(得分:0)

你要制作一个二维数组。遍历每一行,创建一个名为items的数组。在每次迭代开始时,检查当前行的food_cat_id是否与前一行不同。如果是,请将类别推送到结果数组。

您的最后一步是使用json_encode函数将PHP数组编码为JSON字符串。

<?php

// I'm assuming you have fetched the rows from database as associative array and saved it as $rows

$categories = [];
$items = [];
$current_cat_id;
$current_cat_name;

foreach($rows as $row){
  // Check if we have moved onto a new category
  if($row['food_cat_id'] != $current_cat_id && isset($current_cat_id)){
    $category = array(
      "cat_id"    => $current_cat_id,
      "cat_name"  => $current_cat_name,
      "items"     => $items
    );
    array_push($categories, $category);
    $items = []; // Reset $items
  }

  // Add the item to the current items list
  $item = array(
    "item_id"     => $row['food_id'],
    "item_name"   => $row['food_name'],
    "isFav"       => $row['food_fav'],
    "price"       => $row['food_price']
  );
  array_push($items, $item);

  // Remember this category id and name for next iteration
  $current_cat_id = $row['food_cat_id'];
  $current_cat_name = $row['food_cat_name'];
}

// Add the last category on after the loop
$category = array(
  "cat_id"    => $current_cat_id,
  "cat_name"  => $current_cat_name,
  "items"     => $items
);
array_push($categories, $category);

$food = json_encode($categories);