首页 > 解决方案 > 任何人都知道如何在 php 中打印此模式

问题描述

预期输出:在此处输入图像描述 我当前的代码只输出模式,但它不能有更多的梳子:

    $n = 5;
    $n1 = 4;
    for ($i = 0; $i <= $n; $i++) {
        for ($j = 0; $j <= $n1; $j++) {

            if (($i == 0 || $i == 5) && ($j  > 0 and $j  < 3)) {
                if (($i == 0 && $j == 1) || ($i == $n && $j != 2)) {
                    printf("&ensp;");
                }
                printf("$i");
            } elseif (($j == 0 || $j == 3) && ($i != 0 and $i != 5)) {
                if ($j == 0 && $i != 1 && $i != 4) {
                    printf("");
                } elseif (($j == 3 && $i != 1 && $i != 4)) {
                    printf("&ensp;&ensp;");
                } elseif ($j == 0) {
                    printf("&ensp;");
                }
                printf("$i");
            } else {
                printf("&ensp;");
            }
        }
        echo "<be>";


    
`

这是输出,唯一的问题是我如何将梳子相乘。 在此处输入图像描述

标签: php

解决方案


只是为了好玩,我用 JS 编写了它,但转换为 PHP 可能非常简单(String.repeat => str_repeat、、、[].push => array_push[].slice => array_slice

const arr = [];
const output = (x=1, y=1) => {
    for (let k = 0; k < 5; k++) {
        arr.push([' '.repeat(5-k), k, '  '.repeat(k), k, ' '.repeat(5-k)].join(''))
    }
    for (let k = 5; k <= 10; k++) {
        arr.push([' '.repeat(k-5), 10-k, '  '.repeat(10-k), 10-k, ' '.repeat(k-5)].join(''))
    }
    arr.forEach((row, index) => {
        arr[index] = row + row.substring(1).repeat(x - 1);
    });
    const orig = [...arr.slice(1)]
    for (let i = 1; i < y; i++) {
        arr.push(...orig);
    }
    console.log(arr.join('\n'))
}

output(2,3)


推荐阅读