如何访问多维关联数组来打印表格


How can I access a multi-dimensional associative array to print a table?

我正试图打印出一个PHP多维关联数组的表。有班级、作业、学生和分数的数组。

我熟悉MySQL查询,但不知道如何从PHP多维关联数组中打印出表。我访问学生课堂作业分数的思维过程类似于MySQL,但我知道这在这里不起作用。对于一个一维,似乎足够简单,但对于一个多维嵌套的关联数组,我不确定该如何处理?

提前感谢!

<?php
ini_set('display_errors', 'on');
$class=array (
  'cat' => 
  array (
    2 => 
    array (
      'num' => '3',
      'name' => 'Homework',
    ),
  ),
  'assignments' => 
    4 => 
    array (
      'clid' => '5000001001388',
      'assnid' => '1',
      'cat' => '3',
      'due' => '20100802',
      'points' => '5',
      'title' => 'American Revolution',
    ),
  ),
  'students' => 
  array (
    3 => 
    array (
      'stuid' => '460798', // stuid is the student's unique alphanumberic ID string
      'num' => '4',
      'first' => 'Thomas',
      'last' => 'Jefferson',
      'grade' => 'A', // these are summary statistics for the student for the class
      'percent' => '94.7', // these are summary statistics for the student for the class
    ),
  ),
  'scores' => 
  array (
    0 => 
    array (
      'assnid' => '1', // corresponds to assignment's 'assnid'
      'stuid' => '460798', // corresponds to student's 'stuid'
      'score' => '0',  // this is the student's score 
    ),
  ),
);
// display class properties 
print($class["clid"]."<br>"); 
// display all class properties 
foreach ($class["clid"] == $class["assignments"].["clid"] == $class["students"].["assnid"] as $property=>$value) { 
    print($property . " is " . $value . "<br>"); 
} 
?>

所以我使用foreach循环浏览学生、作业和分数。我不知道是否有更好的方法。

echo <<<END
<body>
    <table>
        <thead>
            <tr><th colspan="5" id="title">US History 2012</th></tr>
            <tr>
                <th>Students</th>
                <th>ID</th>
                <th>Grade</th>
                <th>Percentage</th>
                <th>American Revolution</th>
            </tr>
        </thead>
        <tbody>
END;
foreach ($class["students"] as $students){
    echo '<tr class="items">';
        echo '<td>'.$students["first"].' '.$students["last"].'</td>';
        echo '<td>'.$students["stuid"].'</td>';
        echo '<td class="grade">'.$students["grade"].'</td>';
        echo '<td class="perc">'.$students["percent"].'%</td>'; 
    $i = 0;
    $score4Avg = 0; 
    foreach ($class["assignments"] as $assignments){    
        foreach ($class["scores"] as $scores){
            if ($scores["stuid"] == $students["stuid"] && 
                $scores["assnid"] == $assignments["assnid"]){
                echo '<td><input type="text" class="score'.$i.'" value="'.$scores["score"].'" onblur="recalculate();" tabindex="-1"></td>'; 
                $i++;
            }
            if ($scores["assnid"] == $assignments["assnid"] && 
                $assignments["title"] == "American Revolution"){
                $score4Avg += $scores["score"];
            }           
        }   
    }
    echo '</tr>';   
}