根据数组索引在输出中创建换行符

时间:2017-03-30 01:48:08

标签: php arrays

我想显示如下输出:

1 2 3 4
5 6 7 8
9 1 2

我试过这段代码:

$num = ['1','2','3','4','....'];
$size = sizeof($num) / 4;
foreach ($num as $key => $value) {
  echo $value;
  if($key >= round($size){
    echo "<br>"
  }
}

但输出是这样的:

1 2 3 4
5
6
7
8
...

有人可以建议如何编写循环吗?

3 个答案:

答案 0 :(得分:0)

$num= ['1','2','3','4','5','6','7','8','9'];
$size = sizeof($num) / 4;
foreach ($num as $key => $value){
   echo $value;
   if(($key+1) % 4 == 0){
      echo "<br>";
    }
   }

您可以使用模数而不是圆形。酷我还不知道sizeOf!很高兴知道。如果这样可行,请将此标记为正确的答案!

如果你不想写出Num数组中的所有数字,那么另一种方法是将它们推入带有while循环的数组中。

$num= [];
$i = 1;

//Set the Num Variable to have as many numbers as you want without having to manually enter them in
while ($i < 100) {
     array_push($num, $i);
     $i++;
}

//Run the actual code that adds breaks ever 4 lines
$size = sizeof($num) / 4;
foreach ($num as $key => $value){
   echo $value;
   if(($key+1) % 4 == 0){
      echo "<br>";
    }
   }

答案 1 :(得分:0)

很抱歉,如果这个答案看起来与第一个答案相同,但我会更清楚地解释

实现你想要的目标

步骤1:创建for循环

循环将从1开始到它的数组总大小

for ($x = 1; $x <= sizeof($num); $x++){

}

然后在你的循环中

为简单起见,您可以使用三元

这行代码

# if $x variable is equal to limit number which you wanted to break
# $num[$x-1] -> subtract to by 1 because we know array always start at index 0

if ($x % 4 == 0) {
    $num[$x-1]."<br>"; #put a break after it
} else {
    echo $num[$x-1];
}

与此相同

echo ($x % 4 == 0) ? $num[$x-1]."<br>" : $num[$x-1];

所以试试这个

<?php

$num= ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16'];
$size = sizeof($num) / 4;
for ($x = 1; $x <= sizeof($num); $x++){
   echo ($x % 4 == 0) ? $num[$x-1]."<br>" : $num[$x-1];
}

DEMO

答案 2 :(得分:0)

你可以试试这个:

$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 8, 19, 20];

$len = 1;

foreach ($numbers as $number) {
  echo $number . ' ';
  $len++;
  if ($len > 4) {
    echo '<br>';
    $len = 1;
  }     
}