新聞中心
本文操作環(huán)境:windows7系統(tǒng)、php7.1版、DELL G3電腦

創(chuàng)新互聯(lián)建站于2013年開始,先為三河等服務(wù)建站,三河等地企業(yè),進(jìn)行企業(yè)商務(wù)咨詢服務(wù)。為三河企業(yè)網(wǎng)站制作PC+手機(jī)+微官網(wǎng)三網(wǎng)同步一站式服務(wù)解決您的所有建站問題。
php 數(shù)組元素快速去重
1.使用array_unique方法進(jìn)行去重
對(duì)數(shù)組元素進(jìn)行去重,我們一般會(huì)使用array_unique方法,使用這個(gè)方法可以把數(shù)組中的元素去重。
輸出:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
)
去重后,鍵值會(huì)不按順序,可以使用array_values把鍵值重新排序。
2.使用array_unique方法去重效率
'; echo 'run time:'.(float)(($endtime-$starttime)*1000).'ms
'; echo 'use memory:'.getUseMemory(); /** * 獲取使用內(nèi)存 * @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; } ?>
unique count:99 run time:653.39303016663ms use memory:5120kb
使用array_unique方法去重,運(yùn)行時(shí)間需要約650ms,內(nèi)存占用約5m
3.更快的數(shù)組去重方法
php有一個(gè)鍵值互換的方法array_flip,我們可以使用這個(gè)方法去重,因?yàn)殒I值互換,原來(lái)重復(fù)的值會(huì)變?yōu)橄嗤逆I。
然后再進(jìn)行一次鍵值互換,把鍵和值換回來(lái)則可以完成去重。
'; echo 'run time:'.(float)(($endtime-$starttime)*1000).'ms
'; echo 'use memory:'.getUseMemory(); /** * 獲取使用內(nèi)存 * @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; } ?>
unique count:99 run time:12.840032577515ms use memory:768kb
使用array_flip方法去重,運(yùn)行時(shí)間需要約18ms,內(nèi)存占用約2m
因此使用array_flip方法去重比使用array_unique方法運(yùn)行時(shí)間減少98%,內(nèi)存占用減少4/5;
網(wǎng)站題目:php怎么實(shí)現(xiàn)數(shù)組去重
分享鏈接:http://fisionsoft.com.cn/article/cdciidg.html


咨詢
建站咨詢
