foreach在php中的多维数组中循环

时间:2014-11-02 18:16:34

标签: loops multidimensional-array foreach

这是我的PHP代码:

 $marks = array(
    'Mohammad' => array('Phisics' => 50, 'Math' => 80),
    'Arif'     => array('Phisics' => 55, 'Math' => 95),

);

现在我希望使用foreach循环来获取Mohammad和Arif的主题。

2 个答案:

答案 0 :(得分:0)

您可以使用嵌套的foreach循环:

foreach ($marks as $name => $subjects) {
    foreach ($subjects as $subjectName => $subjectMark) {
        echo "${name}'s mark for ${subjectName} is ${subjectMark}.";
    }
}

答案 1 :(得分:0)

试试这个

$marks = array(
    'Mohammad' => array('Phisics' => 50, 'Math' => 80),
    'Arif'     => array('Phisics' => 55, 'Math' => 95),
);

foreach ($marks as $key=>$names) {
    echo "--$key Marks-- <br/>";
    foreach ($names as $key=>$value) {
      echo "$key:$value <br/>";
    }
}

输出

--Mohammad Marks--
Phisics:50
Math:80
--Arif Marks--
Phisics:55
Math:95