2016-11-02 97 views
0

SQl tableJSON输出SQL查询

我如何在JSON输出如下:

"food": { 
     "categories": [{ 
      "cat_id": 122, 
      "cat_name": "bear", 
      "items": [{ 
       "item_id": 1, 
       "item_name": "abc", 
       "isFav": false, 
       "price": 12233.555 
      }, { 
       "item_id": 1, 
       "item_name": "abc", 
       "isFav": false, 
       "price": 12233.555 
      }] 
     }, { 
      "cat_id": 122, 
      "cat_name": "bear", 
      "items": [{ 
       "item_id": 1, 
       "item_name": "abc", 
       "isFav": false, 
       "price": 12233.555 
      }, { 
       "item_id": 1, 
       "item_name": "abc", 
       "isFav": false, 
       "price": 12233.555 
      }] 
     }] 
    } 
+0

使用'json_decode();' – JustOnUnderMillions

+0

这json与数据库中的数据不匹配,所以我不确定你想要什么。 – Jaime

回答

0

你准备做一个2维数组。遍历每一行,创建一个名为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);