我有一个问题,我不知道用foreach()循环来更改每个(X)个结果的输出。
以下是我的foreach()代码:
$dir_handle = 'assets/icons/';
foreach(array_diff(scandir($dir_handle), array('.', '..')) as $file) {
$cut = substr($file, -4);
echo '<a href="action.php?do=changeicon&set=' . $cut . '"><img id="preload_header" src="assets/icons/' . $file . '" /></a><br />';
}我如何得到它,因为1-4有相同的结果,但5-8有一个不同的结果,然后回到1-4?
发布于 2014-03-05 13:57:52
你想在你的前程循环中做一个计数。
$count = 1;
foreach(array_diff(scandir($dir_handle), array('.', '..')) as $file) {
//Check if count is between 1 and 4
if($count >= 1 && $count <= 4) {
//Do something
} else { //Otherwise it must be between 5 and 8
//Do something else
//If we are at 8 go back to one otherwise just increase the count by 1
if($count == 8) {
$count = 1;
} else {
$count++;
}
}
}发布于 2014-03-05 14:02:59
您可以使用%运算符,并结合使用4除法。
foreach ($a as $key => $val) {
$phase = $key / 4 % 2;
if ($phase === 0) {
echo 'here';
}
elseif ($phase === 1) {
echo 'there';
}
}这将每4次循环在两个分支之间切换一次。
正如注释中指出的那样,上面的方法假设数组的键是有序的。如果没有,可以在循环中添加一个计数器变量,如下所示:
$c = 0;
foreach ($a as $val) {
$phase = $c++ / 4 % 2;
if ($phase === 0) {
echo 'here';
}
elseif ($phase === 1) {
echo 'there';
}
}https://stackoverflow.com/questions/22199697
复制相似问题