¿Este código produce el resultado que necesita?
$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
];
}
Contenido de $data
(No he agregado ninguna palabra al párrafo 2 con fines de prueba):
{
"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?"
}
}
}
Tal vez pueda cambiar la estructura de la tabla de su base de datos para obtener todo en una declaración.