while循环内部循环

时间:2013-01-22 18:51:30

标签: php while-loop addition

我很确定你可以在while循环中放置一个while循环,就像之前我做过的那样,但我似乎遇到了一个问题。因为这非常复杂,所以我的代码发布后会解释它。

PHP:

//post vars
$port=$_POST['ports'];
$super=$_POST['super'];
$col=$_POST['columns'];
$row=$_POST['rows'];
//rest of vars
$half_col=$col/$super;
$halfer_col=$col/$super;
$i=1;
$count=1;
$and=1;
$one=1;
$sector=array();
$dat_array=array();

echo $port."<br>";

echo $super."<br>";

echo $col."<br>";

echo $row."<br><br><br><br>";
echo "<h1>here goes nothen</h1><br><br>";

while($count<$port){
    while($i<=$half_col){
        $dat_array[]=$halfer_col;
        $i+=$and;
        $halfer_col-=$and;
        echo "<br>halfer_col:".$halfer_col."<br>";
    }
print_r($dat_array);
$sector[]=implode(',',$dat_array);
$count+=$half_col;
$halfer_col+=$half_col;
}

echo "<br><br>ANNNNNNND...<br><br>";
print_r($sector);

现在,这是用户输入端口:24 super:2 col:12 row:2 结果:

24
2
12
2

here goes nothen

halfer_col:5

halfer_col:4

halfer_col:3

halfer_col:2

halfer_col:1

halfer_col:0
Array ( [0] => 6 [1] => 5 [2] => 4 [3] => 3 [4] => 2 [5] => 1 ) Array ( [0] => 6 [1] => 5 [2] => 4 [3] => 3 [4] => 2 [5] => 1 ) Array ( [0] => 6 [1] => 5 [2] => 4 [3] => 3 [4] => 2 [5] => 1 ) Array ( [0] => 6 [1] => 5 [2] => 4 [3] => 3 [4] => 2 [5] => 1 ) 

ANNNNNNND...

Array ( [0] => 6,5,4,3,2,1 [1] => 6,5,4,3,2,1 [2] => 6,5,4,3,2,1 [3] => 6,5,4,3,2,1 )
基本上,它接受用户输入,将其分解并基于“,”以探针顺序将其破坏。但是从我所知道的,它不是在这里添加:$halfer_col+=$half_col;并且导致数据不增加,任何人的想法?或者甚至解释为什么它不会添加和影响我的内部while循环它的设置方式。

最后的数组应如下所示:

Array ( [0] => 6,5,4,3,2,1 [1] => 12,11,10,9,8,7 [2] => 18,17,16,15,14,13 [3] => 24,23,22,21,20,19 )

2 个答案:

答案 0 :(得分:1)

您可以将代码更改为以下内容:

$port = (int)$_POST['ports'];
$super = (int)$_POST['super'];
$col = (int)$_POST['columns'];
$row = (int)$_POST['rows'];

$colHalf = $col / $super;

$finalArray = array();
for ($i = $port; $i >= 1; $i -= $colHalf) {
    $tempArray = array();
    for ($j = 0; $j < $colHalf; $j++) {
        $tempArray[] = $i - $j;
    }
    $finalArray[] = implode(",", $tempArray);
}
$finalArray = array_reverse($finalArray);

echo "<pre>" . print_r($finalArray, true) . "</pre>";

这将打印你想要的东西(port = 24,super = 2,col = 12,row = 2):

Array
(
    [0] => 6,5,4,3,2,1
    [1] => 12,11,10,9,8,7
    [2] => 18,17,16,15,14,13
    [3] => 24,23,22,21,20,19
)

答案 1 :(得分:0)

你可以尝试在for循环中制作外部。

for(; $count<$port; $count+=$half_col){
    while($i<=$half_col){
        $dat_array[]=$halfer_col;
        $i+=$and;
        $halfer_col-=$and;
        echo "<br>halfer_col:".$halfer_col."<br>";
    }
print_r($dat_array);
$sector[]=implode(',',$dat_array);
$halfer_col+=$half_col;
}