嵌套循环中的减少会影响外循环

时间:2017-05-01 10:25:00

标签: php arrays random html-table nested-loops

尝试显示1-10的随机数,每十四(行)七次,每个数字被分配不同的背景颜色。我想过使用2个嵌套循环,但它没有按预期工作。页面加载了很长时间:“致命错误:超过30秒的最大执行时间......”

我试图删除内循环上的减量并且问题消失但我没有得到预期的结果。提前谢谢。

$colors = array("grey","white","yellow","red","blue","green","brown","purple","orange","black");
$previousNum = array();
$k = 0;
echo '<table>';
while ($k < 15){
    $k++;
    echo '<tr>';
    for($i = 0; $i < 7; $i++){
        $randNum = mt_rand(1, 10);
        if(!in_array($randNum, $previousNum)){
            echo '<td style="background-color: '.$colors[$randNum-1].'; padding: 10px;">';
            echo $randNum;
            echo '</td>';    
            array_push($previousNum, $randNum);
        }else{
            $i--;
        }
    }
    echo '</tr>';
}

2 个答案:

答案 0 :(得分:0)

试试这个,希望这会帮助你。问题是你是,

  

1。$previousNum = array();循环中初始化数组(while

<?php

$colors = array("grey", "white", "yellow", "red", "blue", "green", "brown", "purple", "orange", "black");
$k = 0;

echo '<table>';

while ($k < 15)
{

    echo '<tr>';

    $previousNum = array();
    for ($i = 0; $i < 7; $i++)
    {
        $randNum = mt_rand(1, 10);
        if (!in_array($randNum, $previousNum))
        {

            echo '<td style="background-color: ' . $colors[$randNum - 1] . '; padding: 10px;">';
            echo $randNum;
            echo '</td>';
            array_push($previousNum, $randNum);
        } 
        else
        {
            $i--;
        }
    }

    $k++;
    echo '</tr>';
}

<强>输出:

enter image description here

答案 1 :(得分:0)

您尝试删除减量是正确的。通过运行额外的迭代,减量将对性能产生负面影响。你发布的尝试和其他答案没有纠正这一点,不幸的是他们至少运行了105(7x15)条件声明 - 这不是最佳实践,也不适合SO读者学习。我为您编写了一个新的优化解决方案,没有浪费的声明或迭代,并为深色背景添加了白色字体着色。

echo '<table>';
$whitefonts=['black','purple','brown','grey','blue'];  // for visibility
for($k=0; $k<15; ++$k){
    $colors=["grey","white","yellow","red","blue","green","brown","purple","orange","black"];
    echo '<tr>';
    for($i=0; $i<7; ++$i){
        $key=array_rand($colors);
        $color=$colors[$key];
        unset($colors[$key]);
        echo "<td style=\"background-color:$color;";
            if(in_array($color,$whitefonts)){echo "color:white;";}  //  for visibility
        echo "padding:10px;\">",++$key,"</td>";
    }
    echo '</tr>';
}
echo '<table>';