使用foreach循环更改查询或数据

时间:2017-04-26 06:27:28

标签: php sql yii

我试图通过传递考试ID来制作我的数据......数字是我的学号。数据像这样存储在我的数据库中..

enter image description here

这是我的PHP代码

$sql = "SELECT number, question_id, answer FROM `questions_answers` WHERE exam_id=" . $id;

$command = Yii::app()->db->createCommand($sql);
$data = $command ->query();

This is my for each loop, i am writing to csv file.

foreach($data as $result) {
   fwrite($fp, $result['number'] . "," . $result['answer'] . "\r\n");          
}

这给了我这样的结果..

enter image description here

我希望我的结果是这样的。其中2是Q1给出的数字3100000123的答案,那么3是Q2的答案,1是Q3的答案。同样对于下一个学生编号..我尝试了不同的东西,但没有一个适合我。我怎样才能实现这样的数据?

enter image description here

4 个答案:

答案 0 :(得分:3)

试试这个。

 SELECT number, SUM( IF( question_id =1, answer, NULL ) ) AS Q1, 
 SUM( IF( question_id =2, answer, NULL ) ) AS Q2,
 SUM( IF( question_id =3, answer, NULL ) ) AS Q3,
 FROM test
 GROUP BY number;

答案 1 :(得分:1)

尝试这种方式:

$newArr = array();
foreach($data as $result) {
    $newArr[$result['number']][] = $result['answer'];
}

foreach($newArr as $number=>$answer) {  
    $answer_sring = implode(",",$answer);
    fwrite($fp, $number . ", ".$answer_sring. "\r\n");                  
}

答案 2 :(得分:0)

您可以使用GROUP_CONCAT

$sql = "SELECT number, GROUP_CONCAT(question_id) question_id, GROUP_CONCAT(answer) answer FROM `questions_answers` WHERE exam_id=" . $id ." GROUP BY number";

答案 3 :(得分:0)

您可以使用PIVOT。假设您的源表名为tab。然后,您可以通过以下方式使用PIVOT

SELECT  *
FROM    
(SELECT     question_id,
            answer,
            number
 FROM       tab
) src
PIVOT
(
  MAX(answer)
  FOR question_id IN ([1], [2], [3])
) piv

您可以将其分配给$sql变量:

$sql = '
    SELECT  *
    FROM    
    (SELECT     question_id,
                answer,
                number
     FROM       tab
    ) src
    PIVOT
    (
      MAX(answer)
      FOR question_id IN ([1], [2], [3])
    ) piv'

你可以在这里看到这个 - > http://rextester.com/RJDP17408

希望这有帮助!!!