※ 引述《CuCuGi (咕咕鸡)》之铭言:
: 大家好 小弟最近碰到排序的问题
: 主要是用于 fb的赞数排列
: usort($postArray,'sortByLikeCount');
: function sortByLikeCount($a, $b)
: {
: return ($a["likeCount"] <= $b["likeCount"]) ? -1 : 1;
: }
: 发现如果array过于大量(八万笔左右)会排很久...
: (之前有参考github上python的写法
: postArray.sort(key=lambda x: x["likeCount"], reverse=True)
: 发现排列非常的快)
: 不知道在php中要怎么修改才能更快的完成排序呢?谢谢各位
试试以下
echo "initial: ". microtime() ."<br />" ;
$postArray = array() ;
for($i = 0 ; $i < 100000 ; $i++) {
$postArray[$i]["id"] = $i+1 ;
$postArray[$i]["likeCount"] = rand(1,1000) ;
}
echo "initial END: ".microtime() ."<br />" ;
// 排序 1
echo "Sort 1 Start: ".microtime() ."<br />" ;
$total = array() ;
foreach ($postArray as $key => $row) {
$total[$key] = $row['likeCount'] ;
}
array_multisort($total, SORT_DESC, $postArray) ;
echo "Sort 1 END: ".microtime() ."<br />" ;
// 排序 2: 你的方法
echo "Sort 2 Start:".microtime() ."<br />" ;
usort($postArray,'sortByLikeCount');
function sortByLikeCount($a, $b) {
return ($a["likeCount"] <= $b["likeCount"]) ? -1 : 1;
}
echo "Sort 2 END: ".microtime() ."<br />" ;
echo "END" ;