Re: [請益] 多個array 排序很慢
※ 引述《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
推
09/03 15:28, , 1F
09/03 15:28, 1F
→
09/03 15:29, , 2F
09/03 15:29, 2F
→
09/03 18:00, , 3F
09/03 18:00, 3F
→
09/04 15:11, , 4F
09/04 15:11, 4F
→
09/04 15:13, , 5F
09/04 15:13, 5F
→
09/04 15:14, , 6F
09/04 15:14, 6F
討論串 (同標題文章)
PHP 近期熱門文章
PTT數位生活區 即時熱門文章