如何以这种左右模式排列数字?

Smi*_*iya 12 php loops numbers

我试图在PHP中使用这个模式:

1  2  3  4
8  7  6  5
9 10 11 12
Run Code Online (Sandbox Code Playgroud)

我尝试了这个,但没有成功:

$num = 0;
for ($i=0; $i<=2; $i++) {  
    for ($j=1; $j<=5; $j++) {  
        $num = $j - $i+$num;
        echo $num.""; 
        $num--;
    }  
    echo "</br>";  
}
Run Code Online (Sandbox Code Playgroud)

有人可以帮我吗?

提前致谢...

p01*_*ath 7

这是我使用两个循环可以制作的最简单,最快的代码.使用三个循环更容易,有多种方法可以实现这一点,但根据我的说法,这是最简单的方法.

<?php

$num = 1;
$change = true;
$cols = 5;
$rows = 5;

for ($i = 0; $i < $rows; $i++) {
    if (!$change) {
        $num += ($cols - 1);
    }

    for ($j = 0; $j < $cols; $j++) {
        echo $num . " ";
        if (!$change) {
            $num--;
        } else {
            $num++;
        }
    }

    if (!$change) {
        $num += ($cols + 1);
    }

    $change = !$change;
    echo "<br>";
}
Run Code Online (Sandbox Code Playgroud)

注意:您必须定义$cols变量中的列数.它适用于任何情况.


Jus*_*rty 7

我决定选择array_chunk创建"行" 的方法然后迭代.

$max = 13; // The last number
$cols = 4; // The point at which a new line will start
$arr = array_chunk(range(1, $max), $cols); // Magic ;D

// Print the data.
foreach ($arr as $key => $row) {
    // In case we are wrapping on the far side, this will prevent the row from
    // starting on the left.
    $row = array_pad($row, $cols, ' ');

    // This will reverse every other row
    $row = ($key % 2 === 0) ? $row : array_reverse($row);

    foreach ($row as $value) {
        $value = str_pad($value, strlen($max), ' ', STR_PAD_LEFT);
        echo "{$value} ";
    }
    echo "<br />";
}
Run Code Online (Sandbox Code Playgroud)

输出:

1  2  3  4 
8  7  6  5 
9 10 11 12 
        13 
Run Code Online (Sandbox Code Playgroud)

我也给了你一些选项,以便你可以改变列长度或你想要产生的元素数量.

除非将输出包装在<pre>标记中,否则字符串填充将在浏览器中不可见,因为浏览器一次只显示一个空格.

代码在行动


Xat*_*nev 7

使用for循环并range使用array_reverse:

https://3v4l.org/7QMGl

<?php

$number = 25;
$columnCount = 4;

for($i = 1, $loopCounter = 1; $i <= $number; $i = $i + $columnCount, $loopCounter++) {
    $range = range($i, $i+$columnCount - 1);

    if($loopCounter % 2 === 0) {
        $range = array_reverse($range);
    }

    foreach($range as $n) {
        echo str_pad($n, 2, ' ', STR_PAD_LEFT) . " ";
    }

    echo "\n";

}
Run Code Online (Sandbox Code Playgroud)

我们在每次迭代时都会增加$i,$columnCount所以我们总是可以生成一个必须在此行中输出的数字范围的数组.如果我们必须反转行的数量,这使得它非常简单明了.

str_pad 帮助我们保持正确的间距,例如单个数字

注意:您可能必须换echo "\n";echo "<br>";,如果你正在寻找在浏览器中输出.


Nig*_*Ren 5

只是添加一个简短版本......

$columns = 4;
$rows = 3;
foreach ( array_chunk(range(1,$columns * $rows), $columns) as $row => $line )    {
    echo implode(" ", ($row % 2 == 0 )?$line:array_reverse($line) )."<br />";
}
Run Code Online (Sandbox Code Playgroud)

这个想法是用来range将数字创建成一个数组,然后用array_chunk它将它分成几行.然后使用implode()输出线 - 使用反转的奇数行array_reverse().