Ger den här koden den utdata du behöver?
$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
];
}
Innehållet i $data
(Jag har inte lagt till några ord till punkt 2 i testsyfte):
{
"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?"
}
}
}
Kanske kan du ändra din databastabellstruktur för att få allt i en sats.