如何使用PHP在foreach循环中获取多维数组的键? [英] How to get key of multidimensional array in foreach loop using php?

查看:122
本文介绍了如何使用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"];
}

演示

这篇关于如何使用PHP在foreach循环中获取多维数组的键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆