我的數據庫看起來是這樣的:建立從SQL查詢結果的JSON對象在PHP
我的目標是創建一個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);
這** **真的要提到的PHP和標題和標籤中的mysql。要挑選一些示例 - 如果您要問如何使用PostgreSQL(本機支持JSON數據類型)或從XQuery(它將數據庫查詢結果恢復爲易於轉換的形式一個可以被序列化爲JSON的XML結構)。 –