用两个条件查询PHP

时间:2018-02-15 09:16:48

标签: php arrays database

我正在尝试从我的数据库中的记录列表中创建一个数组。 制作数组并不难,但我需要按特定顺序从数据库中订购记录。

我的数组(按点排序):

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

更明显的例子:

$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,
);

在这种情况下,当我通过points命令数组时,彼得将首先出现,而Victor则有更高的回复率。

我的问题:

我如何订购我的记录,首先是points达到的,如果用户的点数相同,则需要按响应时间(time_left)订购记录?

1 个答案:

答案 0 :(得分:0)

最快的解决方案是在数据库级别订购数组,即添加ORDER BY points ASC, time_left ASC,正如Raymond Nijland告诉你的那样。

如果无法做到这一点,您可以找到here函数示例,以便在不同的键上对数组进行排序:

/**
* 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
        }
    }
}

在您的情况下,您将调用该函数:

array_reorder_keys($all_info, 'points,time_left');