看板 PHP 關於我們 聯絡資訊
※ 引述《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" ; -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.35.82.87 ※ 文章網址: https://www.ptt.cc/bbs/PHP/M.1441170147.A.A69.html
xdraculax: 推實測,但兩個方法要分開測 09/03 15:28
xdraculax: 第一個已經排好第二個就省很多時間 09/03 15:29
xdraculax: 第一個是遞減排第二個是遞增排? 09/03 18:00
IhaveASecret: 我忘了改 Sort 1 的遞增、遞減。 09/04 15:11
IhaveASecret: 10萬筆測下來,Sort 1 就是比 Sort 2 快上 1 秒, 09/04 15:13
IhaveASecret: 原Po看到可以試試看 :) 09/04 15:14