PHP中遍歷數(shù)組的方法?相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。

第一、foreach()
foreach()是一個(gè)用來(lái)遍歷數(shù)組中數(shù)據(jù)的最簡(jiǎn)單有效的方法。
<?php
$urls= array('aaa','bbb','ccc','ddd');
foreach ($urls as $url){
echo "This Site url is $url! <br />";
}
?>顯示結(jié)果:
This Site url is aaa This Site url is bbb This Site url is ccc This Site url is ddd
第二、while() 和 list(),each()配合使用。
<?php
$urls= array('aaa','bbb','ccc','ddd');
while(list($key,$val)= each($urls)) {
echo "This Site url is $val.<br />";
}
?>顯示結(jié)果:
This Site url is aaa This Site url is bbb This Site url is ccc This Site url is ddd
第三、for()運(yùn)用for遍歷數(shù)組
<?php
$urls= array('aaa','bbb','ccc','ddd');
for ($i= 0;$i< count($urls); $i++){
$str= $urls[$i];
echo "This Site url is $str.<br />";
}
?>顯示結(jié)果:
This Site url is aaa This Site url is bbb This Site url is ccc This Site url is ddd
有時(shí)候有人也在問(wèn)這幾種遍歷數(shù)組的方法哪個(gè)更快捷些呢,下面做個(gè)簡(jiǎn)單的測(cè)試就明白了
下面來(lái)測(cè)試三種遍歷數(shù)組的速度
一般情況下,遍歷一個(gè)數(shù)組有三種方法,for、while、foreach。其中最簡(jiǎn)單方便的是foreach。下面先讓我們來(lái)測(cè)試一下共同遍歷一個(gè)有50000個(gè)下標(biāo)的一維數(shù)組所耗的時(shí)間。
<?php
$arr= array();
for($i= 0; $i< 50000; $i++){
$arr[]= $i*rand(1000,9999);
}
function GetRunTime()
{
list($usec,$sec)=explode(" ",microtime());
return ((float)$usec+(float)$sec);
}
######################################
$time_start= GetRunTime();
for($i= 0; $i< count($arr); $i++){
$str= $arr[$i];
}
$time_end= GetRunTime();
$time_used= $time_end- $time_start;
echo 'Used time of for:'.round($time_used, 7).'(s)<br /><br />';
unset($str, $time_start, $time_end, $time_used);
######################################
$time_start= GetRunTime();
while(list($key, $val)= each($arr)){
$str= $val;
}
$time_end= GetRunTime();
$time_used= $time_end- $time_start;
echo 'Used time of while:'.round($time_used, 7).'(s)<br /><br />';
unset($str, $key, $val, $time_start, $time_end, $time_used);
######################################
$time_start= GetRunTime();
foreach($arr as$key=> $val){
$str= $val;
}
$time_end= GetRunTime();
$time_used= $time_end- $time_start;
echo 'Used time of foreach:'.round($time_used, 7).'(s)<br /><br />';
?>測(cè)試結(jié)果:
Used time of for:0.0228429(s) Used time of while:0.0544658(s) Used time of foreach:0.0085628(s)
看完上述內(nèi)容,你們掌握PHP中遍歷數(shù)組的方法的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
分享標(biāo)題:PHP中遍歷數(shù)組的方法-創(chuàng)新互聯(lián)
URL分享:http://chinadenli.net/article2/dcdcic.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供Google、手機(jī)網(wǎng)站建設(shè)、網(wǎng)站導(dǎo)航、做網(wǎng)站、微信公眾號(hào)、電子商務(wù)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容