如何处理PHP语言中的数组


How to deal with arrays in PHP language

<?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>";(,但没有结果.它给了我空的单元格。我怎么能做到这一点?

我想将此回显"<td>" . $row["crd"]. "</td>";列添加到我的代码中。

如评论中所述,已注意到两个错误。

  1. 您将在第二个 foreach 循环中重新声明$data
  2. 您没有在任何地方启动$row,并且试图回显$row["crd"]将导致一个空单元格。

建议的解决方案:

将 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数组中的值(当然,只要该值首先是从数据库中的表中提取的(。

让我知道这是否对您有用。