0

I'm trying to make array filled with different objects. I have set of pages and set of questions. Pages are groups and questions belongs to them.

I want to query first pages, then find out how many questions are within. After that create object for each question and append them into specific pages.

// first get pages so we get grouping and order
$getPages = $conn->prepare("SELECT * FROM pages WHERE event_id = :event_id ORDER BY page_order ASC");
$getPages->bindParam(":event_id", $_SESSION['event_id']);
$getPages->execute();
$pageCount = $getPages->rowCount();
$pages = array();

// get pages
while ($row = $getPages->fetch()) {
    $page = array();
    $page['id'] = $row['id'];
    $page['order'] = $row['page_order'];

    // query for that page
    $stmt = $conn->prepare("SELECT * FROM questions WHERE page_id = :page_id");
    $stmt->bindParam(":page_id", $page['id']);
    $stmt->execute();
    while ($getQuestions = $stmt->fetch()) {
        $question = array();
        $question['id'] = $getQuestions['id'];
        $question['content'] = $getQuestions['content'];
        // push question into questions
        $page['questions'] = $question;
    }

    // push page into pages
    $pages[] = $page;
}

//print pages
echo json_encode($pages);

But sadly it only returns one row for each page...

Javascript object

2
  • 3
    You might want to use $page['questions'][] = $question; instead of $page['questions'] = $question;. Commented Jun 8, 2017 at 7:27
  • 3
    $page['questions'][] = $question; Commented Jun 8, 2017 at 7:27

1 Answer 1

3

It's because your question overwrites each time. Change your code like below

<?php
$page['questions'] = array();
 while ($getQuestions = $stmt->fetch()) {
        $question = array();
        $question['id'] = $getQuestions['id'];
        $question['content'] = $getQuestions['content'];

        // push question into questions
        $page['questions'][] = $question;        
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Or even simpler $page['questions'][] = $getQuestions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.