【问题标题】:Pushing multiple rows of a SQL query into a single PHP array item将 SQL 查询的多行推送到单个 PHP 数组项中
【发布时间】:2011-12-03 10:20:28
【问题描述】:

我现在脑子里放了个屁。我正在从数据库中提取问题和可能的答案,以使用 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 个单独的项。例如,我希望选择数组如下所示:

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 的同一个项目中?**

【问题讨论】:

    标签: php mysql database arrays


    【解决方案1】:

    替换这个:

    array_push($choices, $row2);
    

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

    无论如何,我认为在数组中不包含 1 个元素的数组会更有用。你为什么不这样做?

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      • 2014-02-03
      • 1970-01-01
      相关资源
      最近更新 更多