我使用foreach循环来访问嵌套数组中的记录:
while ($row = mysql_fetch_assoc($result)){
$test_groups[$row['group_name']][] = $row['lab_test'];
}
foreach($test_groups as $group_name => $tests){
echo "<tr><td><span class='test_group_name'>" . $group_name . "</span></td></tr>";
foreach($tests as $test){
echo "<tr><td>" . $test . "</td></tr>";
}
echo "<tr><td> </td></tr>";
}
echo '</table>';
这很好用。现在我需要为嵌套数组添加另一个级别,如:
$departments[$row['department_name']][$row['group_name']][] = $row['lab_test'];
这会起作用,我应该如何调整上面的每个循环来满足这个要求?
答案 0 :(得分:1)
分配给数组的最后应为[]
$departments[$row['department_name']][$row['group_name']][] = $row['lab_test'];
Foreach循环将是:
foreach ($departments as $dep_name => $groups) {
echo $dep_name;
foreach ($groups as $group_name => $tests) {
echo $group_name;
foreach ($tests as $test) {
echo $test;
}
}
}
只需使用echo
es,根据需要制作HTML。