Jump to content

max() function


Schlo_50

Recommended Posts

Hello,

 

If I have the following array, how would I use php's max() function to find the largest number of say the traction attribute?

 

Array
(
    [0] => Array
        (
            [manufacturer] => Nissan
            [model] => 350Z
            [modexp] => 30000
            [traction] => 500
            [aerodynamics] => 3000
            [acceleration] => 1500
            [styling] => 6000
        )

    [1] => Array
        (
            [manufacturer] => Toyota
            [model] => Celica
            [modexp] => 15000
            [traction] => 500
            [aerodynamics] => 3000
            [acceleration] => 1500
            [styling] => 6000
        )

    [2] => Array
        (
            [manufacturer] => Nissan
            [model] => Skyline
            [modexp] => 50000
            [traction] => 500
            [aerodynamics] => 3000
            [acceleration] => 1500
            [styling] => 6000
        )

)

 

 

I've read the information http://php.net/manual/en/function.max.php here but can't figure out how to apply it to my situation?

 

Thanks in advance!

Link to comment
https://forums.phpfreaks.com/topic/181382-max-function/
Share on other sites

Hmm.. I've tried the following but the the car with the largest 'styling' attribute doesn't display. It only shows when it wins overall as well as on the 'styling' attribute.

 

<?php 

function getWinner($chosen, $attr = null) {
    $index = $topStats = 0;

   foreach ($chosen as $key => $data) {
        if ($attr != null && $data[$attr] > $topStats) {
           $topStats = $data[$attr];
           $index = $key;
           continue;
        }
        if (array_sum($data) > $topStats) {
            $index = $key;
            $topStats = array_sum($data);
        }

    }
  return $chosen[$index];
}



echo '<pre>';

// randomSet contains my final array of cars to compare
$winner = getWinner($randomSet);
$winner_on_attribute = getWinner($randomSet, 'styling');

print "<h1>Overall Winner</h1>";
print_r($winner);

print "<h1>Styling attribute Winner</h1>";
print_r($winner_on_attribute);

echo '</pre>';

?>

Link to comment
https://forums.phpfreaks.com/topic/181382-max-function/#findComment-956838
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.