显示编号以在带有循环的php中创建模式

时间:2018-07-08 08:44:11

标签: php loops

谁能解释我创建这样的数字模式

54321 
5432 
543 
54 
5 
54 
543 
5432 
54321

我尝试坚持下去

$star = 5;
$var = 5;
while($star) {
    for ($i = 0; $i < $star; $i++) {
        if ($var <= 0) 
            continue;
        echo $var--;
    }
    echo '<br>';
    $star --;
}

我知道我的代码完全错误,所以可以告诉我更多特定代码吗?

3 个答案:

答案 0 :(得分:0)

像这样的简单解决方案应该起作用:

<?php
$star = 5;
function getPattern($star) {
    for($j = 0; $j < $star; $j++) {
        for($i = $star; $i > $j; $i--) echo $i;
        echo "<br>";
    }
    for($j = $star-1; $j > 0; $j--) {
        for($i = $star; $i > $j-1; $i--) echo $i;
        echo "<br>";
    }
}

getPattern($star);

?>

答案 1 :(得分:0)

您可以试试这个先生

<?php
for($j = 0; $j < 5; $j++) {
    for($i = 5; $i > $j; $i--) echo $i;
    echo "<br>";
}
for($j = 5; $j > 0; $j--) {
    for($i = 5; $i > $j-1; $i--) echo $i;
    echo "<br>";
}
?>

答案 2 :(得分:0)

这是我想出的,我想避免使用双循环,但是在进行迭代时遇到了一些麻烦,该迭代以某种方式切换了大小写以允许大小波动。我发现最简单的方法是执行以下操作:

<?php

//Makes the initial string to use... though I suppose this could just use the array created by range(...)
function makeString($start,$end){
     return implode('', range($start, $end));
}
//The original string we are using and not modifying in case we need it later -- Don't know the context of the code.
$original = makeString(5, 1);
/*
    Let's break down for loops really quick:
        for( [initializing variables -- what values should they start with?];
             [test run after ever iteration to determine if the code should be ran again];
             [code run at the end of every loop])
    With that said, here's what this is doing
    1. set the new $current variable equal to our $original variable, and declare two new arrays $top and $bottom, both being equal to an empty array.
    2. Our check condition is if the string's length is greater than 0 (i.e. a not-empty string)
    3. At the end of every loop, set the $current string to be the substring of the $current string from it's start, to 1 less than its end

*/
for($current = $original, $top = $bottom = []; strlen($current) > 0; $current = substr($current, 0, -1)){
    //append the data to the end of the top array
    $top[] = $current;
    //If our string length is greater than 1 we 'unshift' the current value (place it at the very beginning of the array) 
    if(strlen($current) != 1)
        array_unshift($bottom, $current);
    //Didn't use curly braces here because you don't need them for a single line. 
}

//Implode the merged $top and $bottom arrays, separating each element by a '<br>' to get it on a new line.
$patterned = implode('<br/>', array_merge($top, $bottom));

//... echo it out?
echo $patterned;


?>