将多行SQL查询结果推入单个PHP数组项

3

我现在有点脑袋一片空白。我正在使用PHP和MySQL从数据库中提取问题和可能的答案来动态生成测验。以下是我获得的输出:

    Response id: 3 Question id: 1 Question: What is my middle name? Title: How Well Do You Know Michael
    Array (
        [0] => Array (
            [r_id] => 3
            [question_id] => 1
            [question] => What is my middle name?
            [title] => How Well Do You Know Michael ) ) 
    Array (
        [0] => Array (
            [0] => 1
            [1] => Abe )
        [1] => Array (
            [0] => 2
            [1] => Andrew )
        [2] => Array (
            [0] => 3
            [1] => Andre )
        [3] => Array (
            [0] => 4
            [1] => Anderson ) ) 

从这个 PHP 脚本开始:

// Grab the question data from the database to generate the form
    $query = "SELECT qr.response_id AS r_id, qr.question_id, q.question, quiz.title " . 
         "FROM quiz_response AS qr " . 
         "INNER JOIN question AS q USING (question_id) " . 
         "INNER JOIN quiz USING (quiz_id) " .
         "WHERE qr.user_id = '" . $_SESSION['user_id'] . "'";
    $data = mysqli_query($dbc, $query) or die("MySQL error: " . mysqli_error($dbc) . "<hr>\nQuery: $query");
    $questions = array(); 
    while ($row = mysqli_fetch_array($data, MYSQL_ASSOC)) {
        echo 'Response id: ' . $row['r_id'] . 'Question id: ' . $row['question_id'] . ' Question: ' . $row['question'] . ' Title: ' . $row['title'] . '<br />';
        array_push($questions, $row);
        // Pull up the choices for each question
        $query2 = "SELECT choice_id, choice FROM question_choice " .
        "WHERE question_id = '" . $row['question_id'] . "'";
        $data2 = mysqli_query($dbc, $query2);
        $choices = array();
        while ($row2 = mysqli_fetch_array($data2, MYSQL_NUM))
            array_push($choices, $row2);
    }
    print_r($questions);
    print_r($choices);

然而,我希望$choices数组只有一个项目,而不是4个独立的项目。例如,我希望$choices数组看起来像以下内容:

Array (
    [0] => Array (
        [0] => 1
        [1] => Abe
        [2] => 2
        [3] => Andrew
        [4] => 3
        [5] => Andre
        [6] => 4
        [7] => Anderson )

我的问题是:虽然我从`

`标签中将获得四行独立的文本,但它们如何在页面上以表格的形式呈现?
while ($row2 = mysqli_fetch_array($data2, MYSQL_NUM))
            array_push($choices, $row2);

有没有办法将它们全部推送到数组$choices的同一项中?
1个回答

2

请替换此处:

array_push($choices, $row2);

With

$choices[0][] = $row2[0];
$choices[0][] = $row2[1];

无论如何,我认为在数组中不应该有一个元素的数组会更有用。为什么不这样做呢?

$choices[] = $row2[0];
$choices[] = $row2[1];

我的最后一个评论是,我会选择你当前的选项(行数组,每行都包含列的数组),因为它更接近数据实际表示的方式。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接