我正在尝试通过 MySQL 和 PHP 构建以下 JSON。
每个章节都有一个 id、一个章节标题和一个主题列表。
每个主题都有一个 id 和一个主题区域
{
"Chapters": [
{
"id": "1",
"chapterTitle": "Introduction",
"Topics": [
{
"id": "1",
"topicArea": "C++"
},
{
"id": "2",
"topicArea": "Java"
}
]
},
{
"id": "2",
"chapterTitle": "Getting Started",
"Topics": [
{
"id": "1",
"topicArea": "Start Here"
}
]
}
]
}
但是,如果我尝试以下 PHP 代码 ( 1 ) ,我将无法生成此输出
//Get all chapters
$result = mysql_query("SELECT * FROM chapters");
while ($row = mysql_fetch_array($result))
{
$json[] = $row;
$json2 = array();
$chapterid = $row["id"];
//Fetch all topics within the first book chapter
$fetch = mysql_query("SELECT id,topicArea FROM topics where chapterid=$chapterid");
while ($row2 = mysql_fetch_assoc($fetch))
{
$json2[] = array(
'id' => $row2["id"],
'topicArea' => $row2["topicArea"]
);
}
$json['Topics'] = $json2; //I think the problem is here!
}
echo json_encode($json);