Assuming the "parentid" in the relations table relates to the question.id
$res = $db->query("SELECT q.id
, q.question
, q.pageid
, childid
FROM question q
LEFT JOIN
question_relations r ON q.id = r.parentid;
");
$questions = [];
foreach ($res as $r) {
if (!isset($questions[$r['id']])) {
$questions[$r['id']] = [ 'question' => $r['question'],
'pageid' => $r['pageid'],
'relations'=> []
];
}
$questions[$r['id']]['relations'][] = $r['childid'];
}
$jQuestions = json_encode($questions);
The resulting questions array looks like...
Array
(
[1] => Array
(
[question] => looking for accommodation?
[pageid] => 1A
[relations] => Array
(
[0] => 2
[1] => 3
[2] => 4
)
)
[2] => Array
(
[question] => How do you pay?
[pageid] => 1A1
[relations] => Array
(
[0] => 3
[1] => 4
)
)
[3] => Array
(
[question] => Can you stay with friends?
[pageid] => 2A2
[relations] => Array
(
[0] => 5
[1] => 6
)
)
)
Is that what you are trying to do?