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

问题描述:

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

I need to print the student name and the mark from the following array for a given subject:

$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 循环来显示所有学生及其化学成绩?>

I understand that if I do echo $marks['john']['chemistry']; it will print the mark for the student/subject, but how should I approach a foreach loop for displaying all students and their scores for chemistry?

在php中 foreach() 您可以像这样获取当前项目的密钥

In php foreach() you can get key of current item like this

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

也可以像底层代码一样使用

Also use it like bottom code

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

演示