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

时间:2015-03-03 10:07:24

标签: php multidimensional-array associative-array

我正在尝试打印PHP多维关联数组的表。课程,作业,学生,分数都有阵列。

我熟悉MySQL查询,但我不确定如何从PHP多维关联数组中打印出来。我的思维过程为学生获取分数&#39;该类的分配类似于MySQL,但我知道这在这里不起作用。对于一维,看起来很简单,但是多维嵌套关联数组我不知道如何处理它?<​​/ p>

提前致谢!

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

1 个答案:

答案 0 :(得分:0)

所以我用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>';   
}