0

I have 3 tables "Questions", "Answers", & "Results". I want to fetch multiple rows from 3 tables, one by one and display it sequentialy.

PROGRAM

$questions = Questions::find_by_qpno($qpno);
$answers = Answers::find_by_apno($apno);
$results = Results::find_by_rno($rno);

foreach($questions as $question) {
  echo "Question";
  echo $question->question;
}

foreach($answers as $answer) {
  echo "Answer";
  echo $answer->answer;
}

foreach($results as $result) {
  echo "Result";
  echo $result->remark;
}

OUTPUT

Question
What is software engineering?
Question
What are SDLC models available?

Answer
Software engineering is making softwares
Answer
Waterfall , spiral etc

Remark
It is correct Software engineering is making softwares.
Remark
good Waterfall , spiral etc correct

WANT

Question 1
Answer 1
Remark 1

Question 2
Answer 2
Remark 2

Need a Simple way to nest 3 foreach loops so that I get it in the order Question - Answer - Remark ?

note: I know I could count objects from the SQL query. put $count = count($questions). and use a for loop for($i=1 ; i<=$count ; $i++) and iterate through these three sequentialy. but it looks ugly.

What is the best way to do this ?

IndiGo
  • 101
  • 1
  • 1
  • 9
  • Although the dupe mentions 2 arrays, it uses `foreach( $codes as $index => $code ) {`, which logically extends to however many arrays and works in the same method as the `for` loop you mention. – Nigel Ren Jun 11 '20 at 07:48
  • The _correct_ way to do this, would probably be to not make three separate database queries to begin with, but JOIN the data together in _one_ query. – CBroe Jun 11 '20 at 07:48
  • Is everything in three separate tables? How is the data linked? Can you guarantee that everything in `$questions`, `$answers` and `$results` has the same sorting and same number of elements? In that case I don't see anything wrong with `for($i=1 ; i<=$count ; $i++)`. But if you can join the three tables in a query, that's a much better way of doing this. – Ben Hillier Jun 11 '20 at 07:52

0 Answers0