PHP数组从Mysql循环数组的多个字段

时间:2014-07-28 17:50:29

标签: php mysql arrays loops pivot

我想在以下代码中为我的输出添加更多列。我已经尝试了7个多小时,仍然无法弄清楚如何。

$sub=array();
$query=mysql_query("SELECT regd, name, roll, Subject, 
  SUM( Mark_score ) / SUM( Full_Mark ) *100 AS hl, 
  SUM( Full_Mark ) AS hm
  FROM entry
  WHERE Year = '2013'
  AND Section = 'A'
  AND Name_of_exam = 'First Term Exam'
  GROUP BY regd, Subject");
while ($row=mysql_fetch_assoc($query)){ 
  $sub[$row['regd']][$row['Subject']] = $row['hl']; 
}
$subkey=key($sub); //get the 1st regd key, to be used to get the Subject keys

echo "<table border=1>";
echo "<tr>";
echo '<td>regd</td>';
echo '<td>name</td>';
foreach($sub[$subkey] as $keys=>$vals){
  echo "<td>".$keys."</td>";
}
echo "</tr>";
foreach($sub as $key=>$val){ //loop through each regd value, creating a row
  echo "<tr>";
  echo '<td>'.$key.'</td>';
  echo '<td>'.$name.'</td>';//How do I put name array here?
  foreach($val as $v){ //loop through each Subjects for each regd
    echo '<td>'.$v.'</td>';
  }
  echo "</tr>";
}
echo "</table>";

我想在输出中添加name字段和roll字段。感谢您的投入。

更新了表格:

CREATE TABLE IF NOT EXISTS `entry` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `regd` bigint(20) NOT NULL,
  `name` varchar(30) NOT NULL,
  `rollno` int(11) NOT NULL,
  `section` varchar(5) NOT NULL,
  `univ_roll` varchar(50) NOT NULL,
  `year` year(4) NOT NULL,
  `subject` varchar(50) NOT NULL,
  `Name_of_exam` varchar(40) NOT NULL,
  `Mark_score` int(11) NOT NULL,
  `Full_Mark` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `regd` (`regd`),
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;

1 个答案:

答案 0 :(得分:0)

这看起来像现有代码的插件,因此以下内容应该可以正常运行

$sub = array();
$query = mysql_query("SELECT regd, name, rollno as roll, Subject,
SUM( Mark_score ) / SUM( Full_Mark ) *100 AS hl,
SUM( Full_Mark ) AS hm
FROM entry
WHERE Year = '2013'
AND Section = 'A'
AND Name_of_exam = 'First Term Exam'
GROUP BY regd, Subject");
$array = array(); //create new array
while ($row = mysql_fetch_assoc($query)) {
    $sub[$row['regd']][$row['Subject']] = $row['hl'];

//by doing this, you preserve existing code
    $array[$row['regd']]['roll'] = $row['roll'];
    $array[$row['regd']]['name'] = $row['name'];
}
$subkey = key($sub); //get the 1st regd key, to be used to get the Subject keys

echo "<table border=1>";
echo "<tr>";
echo '<td>regd</td>';
echo '<td>name</td>';
echo '<td>roll</td>';
foreach ($sub[$subkey] as $keys => $vals) {
    echo "<td>".$keys."</td>";
}
echo "</tr>";
foreach ($sub as $key => $val) { //loop through each regd value, creating a row
    echo "<tr>";
    echo '<td>'.$key.'</td>';
    echo '<td>'.$array[$key]['name'].'</td>';
    echo '<td>'.$array[$key]['roll'].'</td>';
    foreach ($val as $v) { //loop through each Subjects for each regd
        echo '<td>'.$v.'</td>';
    }
    echo "</tr>";
}
echo "</table>";