2016-11-02 3 views
0

SQl tableJson Ausgabe SQL-Abfrage

Wie bekomme ich die Ausgabe in JSON wie folgt:

"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

Verwendung 'json_decode();' – JustOnUnderMillions

+0

Das json nicht die Daten in der Datenbank übereinstimmt, so dass ich bin mir nicht sicher, was Sie hier wollen. – Jaime

Antwort

0

Du wirst einen 2-dimensionalen Array machen. Durchlaufen Sie jede Zeile und erstellen Sie ein Array namens items. Überprüfen Sie zu Beginn jeder Iteration, ob sich die aktuelle Zeile food_cat_id von der vorherigen Zeile unterscheidet. Wenn dies der Fall ist, schieben Sie die Kategorie auf das Ergebnis-Array.

Ihr letzter Schritt besteht darin, die json_encode-Funktion zu verwenden, um das PHP-Array als JSON-Zeichenfolge zu codieren.

<?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);