PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, February 15, 2022

[FIXED] Change query or data with foreach loop

 February 15, 2022     php, sql, yii     No comments   

Issue

I am trying to make my data by passing an exam id... the numbers are my student numbers. The data is stored in my db like this..

enter image description here

Here is my php code

$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");          
}

This is giving me result like this..

enter image description here

I want my result to be like this.. Where 2 is the answer of Q1 giving by number 3100000123, then 3 is answer of Q2, 1 is answer of Q3. Similarly for next student number.. I have tried different things but none of them worked for me. How can i achieve my data like this?

enter image description here


Solution

Try this way:

$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");                  
}


Answered By - Ahmed Ginani
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing