PHP / HTML-按行/秒和列/秒配置钻石数量的打印格式

时间:2019-01-08 12:18:56

标签: php html arrays loops echo

我当前正在固定输出格式,应该是这样:

enter image description here

环的数量将由输入 row column 定义。我使用了一个数组来存储输出的每一行,并循环打印包含输出(钻石)的数组,并按行和列重复其打印。

这是我当前的代码(摘要):

    $arr[1] = "   **   ";
    $arr[2] = " *    * ";
    $arr[3] = "*      *";
    $arr[4] = "*      *";
    $arr[5] = " *    * ";
    $arr[6] = "   **   ";

    for($Row_Itr = 1; $Row_Itr <= 6; $Row_Itr++){
       echo "<br>";
        for($repeat_column = 1; $repeat_column <= 2; $repeat_column++){
            for($repeat_row = 1; $repeat_row <= 1; $repeat_row++){
                echo $arr[$Row_Itr];

            }
        }
    }

这是我当前的输出:

行:2,列:2

enter image description here

  

我的源代码可能是什么问题?以及如何修复它   为了实现我的目标输出?

3 个答案:

答案 0 :(得分:2)

您应该使数组从索引0开始,然后遍历行数,然后遍历每个菱形的行数,然后遍历列数。在最内部的列循环之后,输出换行符:

$arr[0] = "&nbsp;&nbsp;&nbsp;**&nbsp;&nbsp;&nbsp;";
$arr[1] = "&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;*&nbsp;";
$arr[2] = "*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*";
$arr[3] = "*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*";
$arr[4] = "&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;*&nbsp;";
$arr[5] = "&nbsp;&nbsp;&nbsp;**&nbsp;&nbsp;&nbsp;";

$rows = 2;
$cols = 2;
$lines = count($arr);

for($r=0; $r<$rows; ++$r) {
  for($l=0; $l<$lines; ++$l) {
    for($c=0; $c<$cols; ++$c) {
      echo $arr[$l];
    }
    echo '<br>';
  }
}

答案 1 :(得分:1)

function draw_diamonds($rows, $cols)
{
    $d = [
        '   **   ',
        ' *    * ',
        '*      *',
        '*      *',
        ' *    * ',
        '   **   ',
    ];

    for($i=0; $i<$rows; $i++)
        for($j=0; $j<6; $j++)
            echo str_repeat($d[$j], $cols), "\n";
}

draw_diamonds(1,2);

输出:

   **      **   
 *    *  *    * 
*      **      *
*      **      *
 *    *  *    * 
   **      **   

答案 2 :(得分:0)

尝试将行循环设置为第一个循环

<?php
    $arr[1] = "&nbsp;&nbsp;&nbsp;**&nbsp;&nbsp;&nbsp;";
    $arr[2] = "&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;*&nbsp;";
    $arr[3] = "*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*";
    $arr[4] = "*&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*";
    $arr[5] = "&nbsp;*&nbsp;&nbsp;&nbsp;&nbsp;*&nbsp;";
    $arr[6] = "&nbsp;&nbsp;&nbsp;**&nbsp;&nbsp;&nbsp;";
    $rowcount = 3;$columncount = 2;
    for($repeat_row = 1; $repeat_row <= $rowcount; $repeat_row++){
        for($Row_Itr = 1; $Row_Itr <= 6; $Row_Itr++){
           echo "<br>";
            for($repeat_column = 1; $repeat_column <= $columncount; $repeat_column++){
                    echo $arr[$Row_Itr];
            }
        }
    }
?>