用于多维数组的嵌套'foreach'

时间:2017-08-17 13:40:08

标签: php html multidimensional-array foreach nested-loops

<?php
$p_23 = array("Name"=>"XYZ","Age"=>"12");
$a_23 = array("Class"=>"5","Sec"=>"A");
$r_23 = array("Personal"=>$p_23,"Academic"=>$a_23);

$p_24 = array("Name"=>"ABC","Age"=>"14");
$a_24 = array("Class"=>"6","Sec"=>"B");
$r_24 = array("Personal"=>$p_24,"Academic"=>$a_24);

$stud = array("23"=>$r_23,"24"=>$r_24);

foreach ($stud as $key => $value) {
    echo $value;
}
?>

使用echo给出错误,
上一期已解决,现在扩大我的问题。 现在我希望这个多维数组使用html标签打印如下     #Roll 23#
      ##学术##
        -class =大于5个
        -sec =&GT;乙
      个人
        -name =&GT; YXZ
        -age =&GT; 12个
    #Roll 24#
      ##学术##
        -class =→6个
        -sec =&gt;一种
      个人
        -name =&GT; ABC
        -Age =&gt; 12

- 带有HTML标记的嵌套foreach部分 -

foreach ($stud as $key => $value) {
    echo "<h1>Roll $key</h1>";
    echo "<ol>";
    foreach ($r_23 as $key => $value) {
    echo "<h2>$key</h2>";
    echo "<ul>";
    foreach ($p_23 as $key => $value){
    echo "<li>$key => $value</li>";}
    echo "</ul>";}
    echo "</ol>";

但它显示了学术和个人密钥的相同值,我并不完全想要。感谢你!!

2 个答案:

答案 0 :(得分:0)

$ value是一个数组,echo只会打印字符串,你需要JSON编码你的$ value并回显它或使用var_dump。如果您的预期输出比这更复杂,那么您需要扩展您的问题。

答案 1 :(得分:-1)

嗯,它是一个多维数组,所以你需要更多foreach()

以下是更新后的代码:

<?php
$p_23 = array("Name"=>"XYZ","Age"=>"12");
$a_23 = array("Class"=>"5","Sec"=>"A");
$r_23 = array("Personal"=>$p_23,"Academic"=>$a_23);
$p_24 = array("Name"=>"ABC","Age"=>"14");
$a_24 = array("Class"=>"6","Sec"=>"B");
$r_24 = array("Personal"=>$p_24,"Academic"=>$a_24);
$stud = array("23"=>$r_23,"24"=>$r_24);
foreach ($stud as $key => $value) {
    foreach($value as $k => $v){
        foreach($v as $kk => $vv) {
            echo $vv;
        }
    }
}
?>

这是你的多维数组:

Array
(
    [23] => Array
        (
            [Personal] => Array
                (
                    [Name] => XYZ
                    [Age] => 12
                )

            [Academic] => Array
                (
                    [Class] => 5
                    [Sec] => A
                )

        )

    [24] => Array
        (
            [Personal] => Array
                (
                    [Name] => ABC
                    [Age] => 14
                )

            [Academic] => Array
                (
                    [Class] => 6
                    [Sec] => B
                )

        )

)