Skip to content
Advertisement

Print a key in a PHP multidimensional array

I have a multidimensional array and I want to print the contents as follows:

Sam
class1: 76
class2: 62
class3: 56
class4: 60

Matt
class1: 76
class2: 62
class3: 56
class4: 60

Dave
class1: 76
class2: 62
class3: 56
class4: 60

Steve
class1: 76
class2: 62
class3: 56
class4: 60

My problem is that I don’t know how to refer to the key of the first sub-array (the names). key($index) just replaces all of the names in the output with “class1”. Here’s my code so far:

$scoreList = array(
    "Sam" => array(
        "class1" => 76,
        "class2" => 62,
        "class3" => 56,
        "class4" => 60,
        ),
    "Matt" => array(
        "class1" => 76,
        "class2" => 62,
        "class3" => 56,
        "class4" => 60,
        ),
    "Dave" => array(
        "class1" => 76,
        "class2" => 62,
        "class3" => 56,
        "class4" => 60,
        ),
    "Steve" => array(
        "class1" => 76,
        "class2" => 62,
        "class3" => 56,
        "class4" => 60,
        ));

printGrade($scoreList["Sam"]);
printGrade($scoreList["Matt"]);
printGrade($scoreList["Dave"]);
printGrade($scoreList["Steve"]);

function printGrade($index) {
    Print key($index)."<br>";
    for($i = 1; $i <= 4; $i++)
    {
        Print "class".$i.": ".$index["class".$i]."<br>";
    };
    echo "<br>";
}

I’m pretty new to web development, so if anyone has any hints I’d really appreciate it!

Edit: Am I getting closer…?

function printGrade($index) {
        foreach ($index as &$value) {
        print array_keys($index).": ".$value."<br>";
    }
    echo "<br>";
}

Advertisement

Answer

Try with this :

foreach($scoreList as $key => $val)
{
    echo $key."</br>";
    foreach( $val as $keyItem => $valKey)
    {
        echo $keyItem ." : ".$valKey."</br>";
    }
}   

Out put:

Sam
class1 : 76
class2 : 62
class3 : 56
class4 : 60
Matt
class1 : 76
class2 : 62
class3 : 56
class4 : 60
Dave
class1 : 76
class2 : 62
class3 : 56
class4 : 60
Steve
class1 : 76
class2 : 62
class3 : 56
class4 : 60
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement