2014-03-05 22 views
1

我有一个问题,我不知道一个foreach()循环来更改每个(x)结果数量的输出。foreach()每4个变化输出

这里是我的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?

+0

你在找什么是[模数运算符](http://www.php.net/manual/en/language.operators .arithmetic.php)。看看这个[示例](http://stackoverflow.com/questions/936242/php-how-do-you-determine-every-nth-iteration-of-a-loop) – gearsdigital

+0

使用增量器,当它达到一个数字可以分为4,做点什么 –

回答

1

你想要做一个计数的foreach循环

$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++; 
     } 
    } 
} 
+0

你先生,很聪明!好工作 – user3352340

+0

感谢您的帮助,做好 – user3352340

+0

@ user3352340没问题。很高兴我能帮到 – Pattle

0

您可以通过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'; 
    } 
} 
+0

这个假设所有的钥匙都是按顺序排列的 – Pattle

+0

@Pattle好点,我添加了一个替代方案。 –