计算循环中的元素

时间:2014-11-19 10:52:44

标签: php arrays string loops

我正在尝试计算循环中的元素以打破每个元素数并以组显示

我的小脚本

$data="house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*";

$exp_filter = explode("*", trim($data));
for ($x = 0; $x <= count($exp_filter); $x++)
{
    print "".$exp_filter[$x]."";
    if ($x%5 == 0)
    {
        print "<br>";   
    }

}

正如你在小脚本中看到的那样,我希望每5回合显示标签
用于休息并以元素组的形式显示。

问题总是显示在第一行中的一个元素,然后是其余元素,并且没有正常工作。

4 个答案:

答案 0 :(得分:1)

$exp_filter的索引从0开始,所以这段代码

if ($x % 5 == 0)
{
    print "<br>";   
}

应该是

if (($x+1) % 5 == 0)
{
    print "<br>";   
}

这是完整的修改代码

$data = "house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*";

$exp_filter = explode("*", trim($data));
for ($x = 0; $x <= count($exp_filter); $x++)
{
    print "".$exp_filter[$x]."";
    if (($x + 1) % 5 == 0)
    {
        print "<br>";   
    }
}

工作示例:http://codepad.org/iEsKK98M

答案 1 :(得分:1)

$data="house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*";

$exp_filter=explode("*",trim($data));
for($x=1;$x<=count($exp_filter);$x++)
{
  print "".$exp_filter[$x]."";
  if($x%5==0) 
  {
    print "<br>";   
  }
}

试试这个。问题是你从0开始,你应该从1开始;)

答案 2 :(得分:1)

<强>的QuickFix

Demo

<?php

$data="house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*";

$exp_filter=explode("*",trim($data));
for($x=1;$x<=count($exp_filter);$x++)
{
print "".$exp_filter[$x]."";
if($x > 0 && $x%5==0) 
{
echo "<br />";   
}

}
?>

答案 3 :(得分:1)

我会使用数组块和内爆:

$data="house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*";

foreach(array_chunk(explode('*', $data), 5) as $chunk){
    echo implode(' ', $chunk) . '<br>';
}

实例:http://codepad.viper-7.com/ED2wHR