Giver denne kode det output, du har brug for?
$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
];
}
Indhold af $data
(Jeg har ikke tilføjet nogle ord til afsnit 2 til testformål):
{
"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?"
}
}
}
Måske kan du ændre din databasetabelstruktur for at få alt i én sætning.