2017-10-13 84 views
1

我的數據庫看起來是這樣的:建立從SQL查詢結果的JSON對象在PHP

enter image description here

我的目標是創建一個SQL查詢,這將產生以下JSON對象:

var data = [ 
     "year1":[ 
      "val1":[ 
       {"DATE":a1, "HEADER":b1, "MESSAGES":c1}, 
       {"DATE":a2, "HEADER":b2, "MESSAGES":c2}, 
       {"DATE":a6, "HEADER":b6, "MESSAGES":c6}, 
      ], 
      "val2":[ 
       {"DATE":a5, "HEADER":b5, "MESSAGES":c5}, 
       {"DATE":a8, "HEADER":b8, "MESSAGES":c8}, 
      ], 
     ], 
     "year2":[ 
      "val3":[ 
       {"DATE":a3, "HEADER":b3, "MESSAGES":c3}, 
       {"DATE":a4, "HEADER":b4, "MESSAGES":c4}, 
       {"DATE":a7, "HEADER":b7, "MESSAGES":c7}, 
      ], 
     ] 
    ]; 

我已經問過一些非常相似的東西。但後來我沒有使用「年」(所以現在有點複雜),只有「val1」,「val2」等值。到目前爲止,我已經試過這樣:

$connect = mysqli_connect("localhost", "root", "root", "Data"); 

$sql_year = "SELECT jaar FROM Data"; 
$result_year = mysqli_query($connect, $sql_year); 
$data_year = array(); 

while ($row = mysqli_fetch_array($result_year, MYSQLI_ASSOC)) { 
    $data_year[$row['jaar']][] = array(
    "maand"=> $row['maand'], 
); 

    $sql_month = "SELECT * FROM Data WHERE jaar =".$row['jaar']; 
    $result_month = mysqli_query($connect, $sql_month); 
    $data_month = array(); 

    while ($row = mysqli_fetch_array($result_month, MYSQLI_ASSOC)) { 
    $data_month[$row['maand']][] = array(
     "day"=> $row['day'], 
     "weekday"=> $row['weekday'], 
     "zaal"=> $row['zaal'], 
     "stad" => $row['stad'] 
    ); 
    } 
} 

header('Content-Type: application/json'); 
echo json_encode($data_year); 
+0

這** **真的要提到的PHP和標題和標籤中的mysql。要挑選一些示例 - 如果您要問如何使用PostgreSQL(本機支持JSON數據類型)或從XQuery(它將數據庫查詢結果恢復爲易於轉換的形式一個可以被序列化爲JSON的XML結構)。 –

回答

1

要建立這種以JSON結構,你必須使用對象結構的這樣一個概念:

<?php 
$username='XXX'; 
$password='XXX'; 
$hostname = 'localhost'; 
$db_name = 'stack1'; 

//connection string with database 
$dbhandle = mysqli_connect($hostname,$username,$password,$db_name) 
or die("Unable to connect to MySQL"); 


//query fire 
$result = mysqli_query($dbhandle,"select DISTINCT year from mydata;"); 
$json_response = array(); 

$array = array(); 

// fetch data in array format 
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { 

    $p_year = $row['year']; 

    $result_year = mysqli_query($dbhandle,"select month from mydata where year='$p_year';"); 
    while ($row = mysqli_fetch_array($result_year, MYSQLI_ASSOC)) { 

      $p_month = $row['month']; 

      $result_month = mysqli_query($dbhandle,"select * from mydata where month='$p_month';"); 
      while ($row = mysqli_fetch_array($result_month, MYSQLI_ASSOC)) { 
       $array[$p_year][$p_month][] = array(
       "DATE" => $row['date'], 
       "HEADER" => $row['header'], 
       "MESSAGE" => $row['message'] 
      ); 

      } 

    } 

} 

array_push($json_response,$array); 
mysqli_free_result($result); 
?> 
+0

但是「$ data_year [$ row ['maand']] [] = array(」year「=> $ row ['year'])」將'maand'和'year'變成了什麼?當你看着我的JSON,這不是我想要的 –

+0

我調整了答案 – Skykaza

+0

它不工作。你是什​​麼意思與'...和如此「 –