msaz87 Posted March 28, 2010 Share Posted March 28, 2010 Hey all, I had a few questions about using associative arrays I was hoping someone could help me with... I'm building an associative array like so: $stat_array = array("Player ID" => $player_id, "Stat" => $stat_sum); And what I would like to do next is 1. find the MAX value of the "Stat" field of the array, and 2. sort the array DESC by the "Stat" field... Originally this was just a one-field array and I was able to accomplish both this way: $max_stat = max($stat_array); arsort($stat_array); But with adding the new field to the array, it doesn't seem like it works any longer... Any help is greatly appreciated -- thanks! Quote Link to comment https://forums.phpfreaks.com/topic/196757-associative-array-questions/ Share on other sites More sharing options...
ignace Posted March 28, 2010 Share Posted March 28, 2010 if it's in the form $array[0]['Stat']; function stat_get_max($stat_array) { $max = 0; if (!is_array($stat_array)) return $max; $sizeof = sizeof($stat_array); for ($i = 0; $i < $sizeof; ++$i) { $max = $stat_array[$i]['Stat'] > $max ? $stat_array[$i]['Stat'] : $max; } return $max; } $max_stat = stat_get_max($stat_array); The sorting will not be possible. Are you retrieving this from a database? Then add this to your query: ORDER BY Stat DESC For the above you can add: max(Stat) AS max_stat to your query to get the max Quote Link to comment https://forums.phpfreaks.com/topic/196757-associative-array-questions/#findComment-1032937 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.