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 关注
- 225 浏览
添加回答
举报