>我有一个函数geturls()
,它以数组的形式返回$urls
$urls[1] $urls[2] .....$urls[44]
但是我不知道$urls
数(有时是44 45 77 ...
我想做很多次循环(在这种情况下为 44 次,但可能会改变)
所以这是我的脚本
function geturls($xml){
//my function
}
$urls = geturls($xml);
$counti = count($urls);
for ($i = 1; $i <= $counti; $i++) {
$modifiedurl = modify($urls[$i]);
echo $modifiedurl;
}
有没有更好的方法可以做到这一点(我确信有更好的方法不使用count())?
您可以使用数组映射函数遍历数组元素。
$modifiedUrls = array_map('modify', $urls);
刚刚对我们的答案进行了测试。
<?php
$start = microtime(true);
$urls = range(1, 1000000);
function modify($url)
{
return "modified_".$url;
}
$modified_urls = [];
foreach ($urls as $url) {
$modified_urls[] = modify($url);
}
// $modified_urls = array_map('modify', $urls);
$end = microtime(true);
$time_elapsed_secs = $end - $start;
echo $time_elapsed_secs;
每根: 0.202~ 毫秒
array_map:0.130~秒
毫秒
使用 foreach()
:
$modified_urls = []; //create new array for modified URLs
foreach($urls as $url){
$modified_urls[] = modify($url); //modify this URL and add it to the array
}
print_r($modified_urls); //output the array