多维数组回声

时间:2016-10-23 08:55:59

标签: php arrays

 Array
(
[abc] => Array
    (
        [1] => 35
        [2] => 30
        [3] => 39
    )

[def] => Array
    (
        [1] => 30
        [2] => 32
        [3] => 29
    )

[ghi] => Array
    (
        [1] => 31
        [2] => 22
        [3] => 39
    )

)

我试图回应这个多维数组。

它适用于print_r,但我想回显它并将输出显示为 abc在1中有35个值,依此类推。

foreach ($marks as $key => $val) {
  echo $val;
}

我知道我必须单独传递每个值,但我不知道它的语法。谢谢 请让我知道如何正确地做到这一点。

2 个答案:

答案 0 :(得分:1)

尝试使用两个for循环

  <?php

    foreach($marks as $key=>$value){

    echo $key;

    foreach($value as $key=>$marks){

    echo $key.'='.$marks.'<br>';
    }
    }
    ?>

根据您的问题

foreach($marks as $key=>$value){

echo $key.'&nbsp;has&nbsp<br>';


foreach($value as $key=>$marks){

echo $marks.'&nbsp;in&nbsp;'.$key.'<br>';

}
}

更新结果

<?php

$marks=[
'mohammad'=>['physics'=>35,'maths'=>30,'chemistry'=>39],
'Qadir'=>['physics'=>30,'maths'=>32,'chemistry'=>29],
'zara'=>['physics'=>31,'maths'=>22,'chemistry'=>39]
];

foreach($marks as $key=>$value){

echo $key.'&nbsp;has&nbsp<br>';


foreach($value as $key=>$marks){

echo $marks.'&nbsp;in&nbsp;'.$key.'<br>';

}
echo "---------------------<br>";
}
?>

输出

mohammad has 
35 in physics
30 in maths
39 in chemistry
---------------------
Qadir has 
30 in physics
32 in maths
29 in chemistry
---------------------
zara has 
31 in physics
22 in maths
39 in chemistry
---------------------

答案 1 :(得分:1)

我相信这可以做你想要的......随意根据自己的喜好修改外观:)

foreach ($marks as $key1 => $person) {
  foreach ($person as $subject => $val2) {
    echo ' '. $key1 .' has '. $person[$subject] .'marks in '. $subject .'<br>';
  }
}

//Array info:
//http://php.net/manual/en/language.types.array.php