简体   繁体   中英

how do i loop through an associative array with multiple values

I just started learning php and I have this issue. I'm trying to loop through this array to get the total value of each key and output the student with the highest number. I'd really appreciate your inputs

$students = array(
        'Mary' => [20,45,12],
        'Grace' => [40,78,56],
        'John' => [61,37,58]
);

The expected output should be Grace but i can't seem to get it to work.

You don't have to loop. Just calculate all the totals

$totals = array_map('array_sum', $students);

then output the key of the array with the maximum total.

echo array_keys($totals, max($totals))[0];

Something like this maybe assuming all grades will be positive

$students = array(
    'Mary' => [20,45,12],
    'Grace' => [40,78,56],
    'John' => [61,37,58]
);

$highest_grade = 0;
$higest_person = "";

foreach($students as $key => $value) {
    $max = max($value);
    if ($highest_grade <= $max) {
        $highest_grade = $max;
        $highest_person = $key;
    }
}
echo $highest_person . '->' . $highest_grade;

Output is using http://phptester.net/

Grace->78

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