用于循环页面

时间:2018-02-06 07:03:44

标签: php for-loop

我试图遍历一定数量的页面来索引它们。

我的代码如下:

$indexedpages = '5';
for ($i = 0; $i <= $indexedpages; $i++) {
$url = 'https://thisisadomain.com/'.$i.'/';
....
rest of code here
....
}

但这并不能解决问题,它只会在 $ indexedpages 中给出的数字一遍又一遍。

我做错了什么?

谢谢

2 个答案:

答案 0 :(得分:1)

正如我所看到的,你只是一遍又一遍地重写价值。 如果您想获取所有页面,请使用array();

示例:

$pages = 5;
$url = array();
for ($i = 0; $i <= $pages; $i++) {
    $url[] = 'https://thisisadomain.com/'.$i.'/';
    //.... rest of code here ....
}
print_r($url);

输出:

Array ( [0] => https://thisisadomain.com/0/ [1] => https://thisisadomain.com/1/ [2] => https://thisisadomain.com/2/ [3] => https://thisisadomain.com/3/ [4] => https://thisisadomain.com/4/ [5] => https://thisisadomain.com/5/ )
这是你想要的吗?希望这会有所帮助。

问候。

答案 1 :(得分:0)

如果你在循环之外使用了$url那么只有一个值,即:你必须在循环中使用$url才能得到所有5个url&#39}。 试试:

$url_arr = array();
$indexedpages = '5';
for ($i = 0; $i <= $indexedpages; $i++) {
 echo $url = 'https://thisisadomain.com/'.$i.'/';
 echo "<br>"; // Displays all values assigned for '$url'

 // OR you can create an array
 $url_arr[] = 'https://thisisadomain.com/'.$i.'/';
}
echo $url; // Only displays last value for '$url'
var_dump($url_arr); // List of all urls.
相关问题