arrays - Query with two conditions PHP

531

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 bypoints Peter will come first while Victor has a higher response rate.

My question:

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

177

Answer

Solution:

The fastest solution is to order the array at database level, i.e. addingORDER 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');

People are also looking for solutions to the problem: php - Symfony 4.0.0 Services argument wiring error

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.