このコードは必要な出力を生成しますか?
$result_w = $conn->query("SELECT * FROM words;");
$results_w = $result_w->fetch_all(MYSQLI_ASSOC);
$words_per_paragraph = [];
foreach($results_w as $key => $row) {
$words_per_paragraph[$row['paragraph_no']][] = $row;
}
$result_p = $conn->query("SELECT * FROM paragraph;");
$results_p = $result_p->fetch_all(MYSQLI_ASSOC);
$data = [];
foreach($results_p as $key => $row) {
$p_no = $row['paragraph_no'];
$words = [];
if(array_key_exists($p_no, $words_per_paragraph)) {
$words = $words_per_paragraph[$p_no];
}
$data[$p_no] = [
'words' => $words,
'paragraph' => $row
];
}
$data
のコンテンツ (テスト目的で段落2に単語を追加していません):
{
"1":{
"words":{
"id":"4",
"book_no":"1",
"paragraph_no":"1",
"word_no":"4",
"word":"you"
},
"paragraph":{
"id":"1",
"book_no":"1",
"paragraph_no":"1",
"paragraph":"hello how are you"
}
},
"2":{
"words":[
],
"paragraph":{
"id":"3",
"book_no":"1",
"paragraph_no":"2",
"paragraph":"I'm fine and you?"
}
}
}
データベーステーブルの構造を変更して、すべてを1つのステートメントにまとめることができるかもしれません。