0

I'm trying to make an array from a list of records from my database. Making the array is not hard, but I need to order the records from the database in a specific order.

My array (ordered by points):

$all_info[$team_id] = array(
     'nickname'     => $nickname,
     'points'       => $points_pr_round,
     'time_left'    => $time_left,
     'total_number' => $points_pr_round + $time_left,
);

More visible example:

$all_info[3] = array(
      'nickname'     => John,
      'points'       => 60,
      'time_left'    => 132,
      'total_number' => 60 + 132,
 );
$all_info[5] = array(
      'nickname'     => Victor,
      'points'       => 78,
      'time_left'    => 120,
      'total_number' => 78 + 120,
);
$all_info[2] = array(
      'nickname'     => Peter,
      'points'       => 78,
      'time_left'    => 125,
      'total_number' => 78 + 125,
);

In this case, when I order the array by points Peter will come first while Victor has a higher response rate.

My question:

How can I order my records, first on points achieved and if users have the same amount of points the records need to be ordered by response time (time_left)?

Stephen King
  • 581
  • 5
  • 18
  • 31

1 Answers1

0

The fastest solution is to order the array at database level, i.e. adding ORDER BY points ASC, time_left ASC, as Raymond Nijland told you.

If this is not possible, you can find here an example of a function to sort an array on different keys:

/**
* function array_reorder_keys
* reorder the keys of an array in order of specified keynames; all other nodes not in $keynames will come after last $keyname, in normal array order
* @param array &$array - the array to reorder
* @param mixed $keynames - a csv or array of keynames, in the order that keys should be reordered
*/
function array_reorder_keys(&$array, $keynames){
    if(empty($array) || !is_array($array) || empty($keynames)) return;
    if(!is_array($keynames)) $keynames = explode(',',$keynames);
    if(!empty($keynames)) $keynames = array_reverse($keynames);
    foreach($keynames as $n){
        if(array_key_exists($n, $array)){
            $newarray = array($n=>$array[$n]); //copy the node before unsetting
            unset($array[$n]); //remove the node
            $array = $newarray + array_filter($array); //combine copy with filtered array
        }
    }
}

In your case, you would invoke that function as:

array_reorder_keys($all_info, 'points,time_left');
Pierre François
  • 5,850
  • 1
  • 17
  • 38
  • Thx for your answer. array_multisort() did it for me – Lucas Hendriks Feb 15 '18 at 12:40
  • @LucasHendriks: if you post the line of code invoking `array_multisort()` (v.gr as a comment), I could edit my answer to improve it and help more people. The more people are happy with this question and its answer, the more your reputation will increase. – Pierre François Feb 15 '18 at 16:49