2 回答

TA貢獻1773條經驗 獲得超3個贊
因此,我首先美化您的 JSON 和 PHP,然后重新格式化您的代碼,以便更容易理解所需的數據層次結構以及編碼的數據層次結構。這是重新格式化:
<?php
foreach ($db_found->query($sql) as $row) {
$json_array[] =
[
'start_date' =>
[
'minute' => $row['min'],
'hour' => $row['hour'],
'month' => $row['mo'],
'day' => $row['day'],
'year' => $row['yr']
],
'text' =>
[
'text' => $row['text'],
'group' =>
[
'group' => $row['callsign']
]
]
];
}
$data = ["events" => $json_array];
echo json_encode($data);
?>
您可以看到“組”數組位于“文本”數組內。在重新格式化您想要的 JSON 之后,我認為這就是您要尋找的內容:
以及產生我認為您正在尋找的輸出的代碼:
<?php
foreach ($db_found->query($sql) as $row) {
$data["events"][] =
[
'start_date' =>
[
'minute' => $row['min'],
'hour' => $row['hour'],
'month' => $row['mo'],
'day' => $row['day'],
'year' => $row['yr']
],
'text' =>
[
'text' => $row['text']
],
'group' =>
[
'group' => $row['callsign']
]
];
}
echo json_encode($data);
?>
筆記:
我選擇了這種特殊的格式,因為它是理解層次結構的最簡單方法。通常我不會
[
像那樣把它放在自己的線上,但在這種情況下它更容易處理。我選擇
[]
了數組定義,array()
因為它的視覺噪音要少得多,因此更容易理解我
$data["events"][] =
在循環中使用了,因為我認為它使您定義的數據更加清晰?;蛘撸铱赡軙@樣做,$events[] =
或者$eventsJson[] =
讓變量清楚地表明它應該持有什么信息,然后執行$data=['events'=>$eventsJson];
$row[string]
不向前兼容。見https://www.php.net/manual/en/language.types.array.php#language.types.array.foo-bar

TA貢獻1821條經驗 獲得超6個贊
試試這個代碼塊
$json_array[] =
array(
'start_date' =>
array(
'minute' => $row[min],
'hour' => $row[hour],
'month' => $row[mo],
'day' => $row[day],
'year' => $row[yr]
),
'text' =>
array('text' => $row[text]), // this is the change
'group' =>
array('group' => $row[callsign]) // so here matching bracket must be maintain
);
OUTP 結構是您想要的帶有空數據的結構,因為我沒有循環數據
{
"events": [
{
"start_date": {
"minute": null,
"hour": null,
"month": null,
"day": null,
"year": null
},
"text": {
"text": null
},
"group": {
"group": null
}
}
]
}
- 2 回答
- 0 關注
- 247 瀏覽
添加回答
舉報