如何使用php获取foreach循环中多维数组的键?

时间:2017-02-19 18:16:31

标签: php loops multidimensional-array foreach

我需要为给定主题打印以下数组中的学生姓名和标记:

$marks = [
    "john" => ["physics" => 30, "maths" => 55, "chemistry" => 66],
    "jack" => ["physics" => 44, "maths" => 19, "chemistry" => 87],
    "mark" => ["physics" => 77, "maths" => 66, "chemistry" => 67],
];

我理解,如果我echo $marks['john']['chemistry'];它会打印出学生/科目的标记,但我应该如何接近 foreach 循环来显示所有学生及其化学成绩?

1 个答案:

答案 0 :(得分:3)

在php foreach()中,您可以获得当前项目的密钥

foreach ($array as $key=>$item){...}

也像底码

一样使用它
foreach ($marks as $name=>$scores){
    echo $name .":". $scores["chemistry"];
}

查看demo

中的代码结果