Jump to content

Associative array questions


msaz87

Recommended Posts

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!

Link to comment
https://forums.phpfreaks.com/topic/196757-associative-array-questions/
Share on other sites

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

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.