简体   繁体   中英

How to print array element with keys & values in PHP?

I'm learning array and loop in php. But can't print the array with keys & values. How can I do this?

<?php
$marks = array (
    "Alice" => array (
        "physics" => "60",
        "math" => "65"
    ),
    "Bob" => array (
        "physics" => "40",
        "math" => "45"
    )
);

foreach ( $marks as $key => $value) {
    foreach ( $key as $key2 => $value2 ) {
        echo $key . " : " . $key2 . " - " . $value2 . "<br>";
    };
};
?>

In the nested foreach you have to iterate over the $value which holds the array.

foreach ( $marks as $key => $value) {
   foreach ( $value as $key2 => $value2 ) {
   // -------^^^^^^-------
      echo $key . " : " . $key2 . " - " . $value2 . "<br>";
   }
};

Use this

foreach ( $marks as $key => $value) {
     foreach ( $value as $key2 => $value2 ) {
        echo $key . " : " . $key2 . " - " . $value2 . "<br>";
          }
       }

This way it could be more readable to fix it and clear up confusion:

     $marks = array(
        'Alice' => array(
            'physics' => 60,
            'math' => 65,
        ),
        'Bob' => array(
            'physics' => 40,
            'math' => 45,
        ),
    );

    // Loop students
    foreach($marks as $name => $grades){

        // Loop their grades
        foreach ($grades as $subject => $score){
            echo $name . ' : ' . $subject . ' - ' . $score . '<br>';
        }
    }

Please note that the numbers are without quotes. This will allow you to use them as numbers to do further calculations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM