douao1579 2017-03-19 00:33
浏览 30
已采纳

PHP函数两个表中的两个循环

I've got 2 tables one holds questions and one holds answers. I was wondering if I can grab and echo them through a function. So basically loop through the questions and echo question + answers.

Questions
+------+-------------------------------+
| q_id | question                      |
+------+-------------------------------+
| 1    | What is your favorite color?  |
+------+-------------------------------+

Answers
+------+------+-----------+
| a_id | q_id | answer    |
+------+------+-----------+
| 1    | 1    | Green     |
+------+------+-----------+
| 2    | 1    | Blue      |
+------+------+-----------+
| 3    | 1    | Yellow    |
+------+------+-----------+

What I have done until now

function Questionaire()
{
    if(!$this->DBLogin())
    {
        $this->HandleError("Database login failed!");
        return false;
    }

    $result = array();

    $conn = $this->connection;
    $query = "SELECT * FROM `questions` WHERE status = 1";
    $result = $conn->query($query);

    while ($row = $result->fetch()) {
        $result[] = $row['question'];
    }

    return $result;
}
  • 写回答

2条回答 默认 最新

  • douwu0882 2017-03-19 00:39
    关注

    Something like this?

    function Questionaire()
    {
        if(!$this->DBLogin())
        {
            $this->HandleError("Database login failed!");
            return false;
        }
    
        $data = array();
    
        $conn = $this->connection;
        $query = "SELECT * FROM `questions` WHERE status = 1";
        $result = $conn->query($query);
    
        while ($row = $result->fetch()) {
            $row['answers'] = [];
            $query2 = "SELECT * FROM `answers` WHERE q_id = '$row[q_id]'";
            $result2 = $conn->query($query2);
            while($row2 = $result2->fetch())$row['answers'][] = $row2;
            echo "Question: <pre>".var_export($row, true)."</pre>";
            $data[] = $row;
        }
    
        return $data;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 DEV-C++编译缺失
  • ¥33 找熟练码农写段Pyhthon程序
  • ¥100 怎么让数据库字段自动更新
  • ¥15 antv g6 力导向图布局
  • ¥15 quartz框架,No record found for selection of Trigger with key
  • ¥15 锅炉建模+优化算法,遗传算法优化锅炉燃烧模型,ls-svm会搞,后面的智能算法不会
  • ¥20 MATLAB多目标优化问题求解
  • ¥15 windows2003服务器按你VPN教程设置后,本地win10如何连接?
  • ¥15 求一阶微分方程的幂级数
  • ¥15 关于#线性回归#的问题:【统计】回归系数要转化为相关系数才能进行Fisher' Z转化吗(相关搜索:回归模型)