0

是否甚至可以对数组进行排序,使得一个元素(在这种情况下,与当前用户匹配的元素)冒泡到顶部,而其余的则正确排序在其下方?

我试图这样做(是的,我的 PHP 版本没有关闭,这很遗憾)但没有运气。

    uasort($output, create_function('$a,$b',                                                        
        'if( $a["user_id"] == '.$this->user['id'].') { return -1; }'.                               
        'elseif( $b["user_id"] == '.$this->user['id'].') { return -1; }'.                           
        'elseif( $b["percent"] == $a["percent"]) { return strcasecmp($a["username"], $b["username"]); 
        'elseif($a["percent"] < $b["percent"]) { return 1; }'.                                      
        'elseif($a["percent"] > $b["percent"]) { return -1; }'.                                     
        'else { return 0; }'                                                                        
    ));

我认为这是最好的方法,因为无论如何我都必须对数组进行排序 - 但我愿意接受建议。

提前谢谢。

4

1 回答 1

1

最好的方法可能是这样做:

function sortWithUserFirst($output) {
    $user_ids = Set::extract('/user_id', $output); // list of user ids
    $user_id_key = array_search($this->user['id']);
    $user_record = $output[$user_id_key];
    unset($output[$user_id_key]); // clear the key => value pair
    uasort($output, your_sort_function);
    array_unshift($output, $user_record); // put the user record at the beginning of the array
}
于 2012-11-20T15:28:30.123 回答