Jump to content

best results


Go to solution Solved by Barand,

Recommended Posts

hi all,

 

im trying to get best results from this list

 

name--------good---------best time

carl------------1    ---------14

john------------2    ---------25

benny----------2    ---------21

 

 

good represent right answer and bet time represent speed.

 

i need to find who answer most and the least time.

 

so the best from the example is 2-21

 

i have put the results in array and found the max(good) and the min(best time) 

 

how can i found that benny won in table example, he had 2 good and is best time is better then john, carl is out because he have only 1 good.

 

thanks

 

Link to comment
https://forums.phpfreaks.com/topic/293684-best-results/
Share on other sites

  • Solution

Just in case you aren't using a database, you can sort the array by good(DESC), time(ASC) then take the the first element.

$results =  [
                ['name'=>'carl',  'good'=>1, 'time'=>14],
                ['name'=>'john',  'good'=>2, 'time'=>25],
                ['name'=>'benny', 'good'=>2, 'time'=>21]
            ];
usort($results, 'resultSort');
echo $results[0]['name'];    // benny


function resultSort($a, $b) {
    // compare by 'good' DESC
    $x = $b['good'] - $a['good'];
    if ($x==0) {
        // if same, compare by 'time' ASC
        return $a['time'] - $b['time'];
    }
    else return $x;
}
Link to comment
https://forums.phpfreaks.com/topic/293684-best-results/#findComment-1501808
Share on other sites

i changed it to:

 

 

$results =  array(
                array('name'=>'carl',  'good'=>4, 'time'=>14),
                array('name'=>'john',  'good'=>4, 'time'=>25),
                array('name'=>'benny', 'good'=>5, 'time'=>21)
            );
usort($results, 'resultSort');
echo $results[0]['name'];    // benny
Link to comment
https://forums.phpfreaks.com/topic/293684-best-results/#findComment-1502146
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.