Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.