7spark Posted July 18, 2013 Share Posted July 18, 2013 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 https://forums.phpfreaks.com/topic/280284-highest-values-in-multidimensional-array/ Share on other sites More sharing options...
.josh Posted July 18, 2013 Share Posted July 18, 2013 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 https://forums.phpfreaks.com/topic/280284-highest-values-in-multidimensional-array/#findComment-1441266 Share on other sites More sharing options...
Barand Posted July 18, 2013 Share Posted July 18, 2013 or just sort the array on descending values of score function mysort($a, $b) { return $b[1] - $a[1]; // for ASC sort on element 1 (score), reverse a and b } usort($array, 'mysort'); // sort the array DESC The highest score will be the record at $array[0] Link to comment https://forums.phpfreaks.com/topic/280284-highest-values-in-multidimensional-array/#findComment-1441273 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.