Jump to content

Highest Values in Multidimensional Array


7spark

Recommended Posts

I have an array similar to this:

array(5) { [0]=> string(2) "32" [1]=> string(2) "67" [2]=> string(19) "2013-07-15 15:56:28" [3]=> string(1) "1" [4]=> string(4) "Fail"}
array(5) { [0]=> string(2) "32" [1]=> string(2) "89" [2]=> string(19) "2013-09-15 13:50:34" [3]=> string(1) "2" [4]=> string(4) "Pass"}
array(5) { [0]=> string(2) "37" [1]=> string(2) "55" [2]=> string(19) "2013-07-15 16:36:12" [3]=> string(1) "1" [4]=> string(4) "Fail"}
array(5) { [0]=> string(2) "39" [1]=> string(2) "92" [2]=> string(19) "2013-08-15 15:46:20" [3]=> string(1) "1" [4]=> string(4) "Pass"}

The first value displays a content ID, the second a score, the third a date, the fourth an attempt number (no limit), and the fifth a result. I want to print these values in the browser, but if there is more than one attempt, I only want to print the one with the highest score but I can't seem to get it working. I am pretty new to PHP so if someone could provide some sample code to show me how it could be done it would be a huge help. Thanks!

Link to comment
Share on other sites

Where is this data coming from? If it is coming from a database then you should be able to alter your query to only select the highest value.

 

If not, then you can do something like this:

 

// init new array
$newArrayList = array();
// loop through current multi-dim array
foreach ($arrayList as $array) {
  // if entry for id is not yet set or if the current attempt is higher than previous attempt, add to newArrayList
  if ( !isset($newArrayList[$array[0]]) || ($array[3]>$newArrayList[$array[0]][3]) )
    $newArrayList[$array[0]] = $array;
}
note: fyi for future reference, post the result of serialize($array) instead of just a var_dump; it makes it a lot easier for people to quickly reconstruct the array to play with.
Link to comment
Share on other sites

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.