如何用PHP语言处理数组

时间:2016-05-07 19:19:10

标签: php html5

<?php

$con = mysqli_connect('localhost', 'root', '');
if(!$con)
{
    die("not ok");
}

mysqli_select_db($con,"uoh");  


$q1 = "SELECT * FROM student_record INNER JOIN degree_plan ON
 student_record.course_number = degree_plan.course_number 
 INNER JOIN courses ON student_record.course_number = 
 courses.course_number where student_record.id  = 201102887 AND degree_plan.major='COE'";

$result = mysqli_query($con , $q1 ) ;
$data = array();
while($row = mysqli_fetch_array($result))
{
    $data[$row["term_no"]][] =  array(
        'code' => $row["code"],
        'grade' => $row["grade"]
    );

}


echo '<table width="200" border="1">';
   echo "<tr>";
   echo "<th>courses</th>";
   echo "<th>terms</th>";
   echo "<th>grades</th>";
   echo "</tr>";

foreach($data as $term=>$otherrow) {
    $count = 0;
    foreach ($otherrow as $data) {
        if($count == 0) {
            echo "<tr>";
            echo "<td>" . $data["code"]. "</td>";
            echo '<td rowspan="'.count($otherrow).'">' . $term. '</td>';
            echo "<td>" . $data["grade"]. "</td>";
            echo "</tr>";
            }

        else 

        {
            echo "<tr>";
            echo "<td>" . $data["code"]. "</td>";
            echo "<td>" . $data["grade"]. "</td>";
            echo "</tr>";
        }
        $count++;
    }
}
echo "</table>";

?>

我有这个代码并且它工作得很好但是当我想添加更多列时我遇到了问题。 我试图添加第四列(echo "<td>" . $row["crd"]. "</td>";),但没有结果。它给我空单元格。我怎么能这样做?

我想在我的代码中添加此echo "<td>" . $row["crd"]. "</td>";列。

1 个答案:

答案 0 :(得分:0)

正如评论中所提到的,有两个错误被注意到了。

  1. 您将在第二个foreach循环中重新声明$data
  2. 您没有在任何地方发起$row,尝试回复$row["crd"]会导致空单元格。
  3. 建议的解决方案:

    将foreach循环中$data值的名称更改为$row,从而同时解决这两个问题:

    foreach($data as $term=>$otherrow) {
        $count = 0;
        foreach ($otherrow as $row) {
            if($count == 0) {
                echo "<tr>";
                echo "<td>" . $row["code"]. "</td>";
                echo '<td rowspan="'.count($otherrow).'">' . $term. '</td>';
                echo "<td>" . $row["grade"]. "</td>";
                echo "</tr>";
                }
    
            else 
    
            {
                echo "<tr>";
                echo "<td>" . $row["code"]. "</td>";
                echo "<td>" . $row["grade"]. "</td>";
                echo "</tr>";
            }
            $count++;
        }
    } 
    

    现在添加echo "<td>" . $row["crd"]. "</td>";时,它应该回显存储在$row数组中的值(只要数据首先从数据库中的表中提取出来)。< / p>

    如果这对您有用,请告诉我。