Schlo_50 Posted November 13, 2009 Share Posted November 13, 2009 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 More sharing options...
Mchl Posted November 13, 2009 Share Posted November 13, 2009 You can't. It will only work on single dimension arrays. To find max value of traction you can do $maxTraction = 0; foreach($cars as $model) { if($model['traction'] > $maxTraction) { $maxTraction = $model['traction']; } } Link to comment https://forums.phpfreaks.com/topic/181382-max-function/#findComment-956804 Share on other sites More sharing options...
Schlo_50 Posted November 13, 2009 Author Share Posted November 13, 2009 That would be why I'm struggling. Thanks for the other suggestion. Link to comment https://forums.phpfreaks.com/topic/181382-max-function/#findComment-956828 Share on other sites More sharing options...
Schlo_50 Posted November 13, 2009 Author Share Posted November 13, 2009 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 More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.