1.使用array_unique方法進行去重
對數組元素進行去重,我們一般會使用array_unique方法,使用這個方法可以把數組中的元素去重。
123456
輸出:
Array( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 7 [7] => 8 [8] => 9)123456789101112
去重後,索引值會不按順序,可以使用array_values把索引值重新排序。
2.使用array_unique方法去重效率
';echo 'run time:'.(float)(($endtime-$starttime)*1000).'ms
';echo 'use memory:'.getUseMemory();/** * 擷取使用記憶體 * @return float */function getUseMemory(){ $use_memory = round(memory_get_usage(true)/1024,2).'kb'; return $use_memory;}/** * 擷取microtime * @return float */function getMicrotime(){ list($usec, $sec) = explode(' ', microtime()); return (float)$usec + (float)$sec;}?>1234567891011121314151617181920212223242526272829303132333435363738394041
unique count:99
run time:653.39303016663ms
use memory:5120kb
使用array_unique方法去重,已耗用時間需要約650ms,記憶體佔用約5m
3.更快的數組去重方法
php有一個索引值互換的方法array_flip,我們可以使用這個方法去重,因為索引值互換,原來重複的值會變為相同的鍵。
然後再進行一次索引值互換,把鍵和值換回來則可以完成去重。
';echo 'run time:'.(float)(($endtime-$starttime)*1000).'ms
';echo 'use memory:'.getUseMemory();/** * 擷取使用記憶體 * @return float */function getUseMemory(){ $use_memory = round(memory_get_usage(true)/1024,2).'kb'; return $use_memory;}/** * 擷取microtime * @return float */function getMicrotime(){ list($usec, $sec) = explode(' ', microtime()); return (float)$usec + (float)$sec;}?>123456789101112131415161718192021222324252627282930313233343536373839404142
unique count:99
run time:12.840032577515ms
use memory:768kb
使用array_flip方法去重,已耗用時間需要約18ms,記憶體佔用約2m
因此使用array_flip方法去重比使用array_unique方法已耗用時間減少98%,記憶體佔用減少4/5;