2016-11-02 98 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);