0

好的,首先这是我的代码:

<table border="1" style="text-align:center;" width="400px;" height="400px;">

 <?php

    $table = range(1, 9);
    shuffle($table);

    for($i=0; $i<9; $i++){

        echo '<tr id="r'.$i.'">';

        for ($j=0; $j<9 ; $j++) { 
            echo '  <td id="r'.$i.'d'.$j.'">'.$table[$j].'</td>';
        }

        echo '</tr>';
    }

?>

</table>

我要做的就是制作一个 9x9 的正方形,每行和每列都有 1-9 的唯一值。但是当我运行我的代码时,它只显示列而不是行的随机数。我想要从 1 到 9 的整个块中的随机数。

请帮我...

4

5 回答 5

0

试试这个:在内部循环之前打乱 $table

<table border="1" style="text-align:center;" width="400px;" height="400px;">
 <?php
    $table = range(1, 9);
    for($i=0; $i<9; $i++){
        echo '<tr id="r'.$i.'">';
        shuffle($table);
        for ($j=0; $j<9 ; $j++) { 
            echo '  <td id="r'.$i.'d'.$j.'">'.$table[$j].'</td>';
        }
        echo '</tr>';
    }

?>
</table>
于 2013-02-14T07:43:13.620 回答
0

如果您需要行和列中的唯一值,请查看此链接

您可以使用该代码或重新使用生成功能,如下所示:

<table border="1" style="text-align:center;" width="400px;" height="400px;">

$grid = generate();
foreach ($grid as $i => $row){
    echo '<tr id="r'.$i.'">';
    foreach ($row as $j => $cell){
        echo '  <td id="r'.$i.'d'.$j.'">'. $cell .'</td>';
    }
    echo '</tr>';
}



function generate() {
    $vGrid = $hGrid = array();
    $numbers = range(1,9);      
    for($x = 0; $x < 9; $x++) {
        for($y = 0; $y < 9; $y++) {
            $hGrid[$x] = !isset($hGrid[$x]) ? array() : $hGrid[$x];
            $vGrid[$y] = !isset($vGrid[$y]) ? array() : $vGrid[$y];
            $options = array_diff($numbers,$hGrid[$x],$vGrid[$y]);
            $key = array_rand($options);
            if(!isset($options[$key])) {
                return generate();
            }
            $val = $options[$key];
            $hGrid[$x][$y] = $vGrid[$y][$x] = $val;
        }
    }
    return $hGrid;
}

?>

于 2013-02-13T16:29:12.920 回答
0

你的数组$table实际上并没有在循环内改变,这就是问题所在。您需要shuffle($table)在第一个循环 ( for($i=0; $i<9; $i++)) 中运行。

于 2013-02-13T15:44:53.253 回答
0

shuffle在第一个for循环内调用。你只是洗牌一次,所以你只是一遍又一遍地重复同一行:

 <?php

    $table = range(1, 9);

    for($i=0; $i<9; $i++){
        shuffle($table);
        echo '<tr id="r'.$i.'">';

        for ($j=0; $j<9 ; $j++) { 
            echo '  <td id="r'.$i.'d'.$j.'">'.$table[$j].'</td>';
        }

        echo '</tr>';
    }

?>
于 2013-02-13T15:44:16.393 回答
0

我不知道这是否是你需要的

看看这段代码..

    <table border="1" style="text-align:center;" width="400px;" height="400px;">

 <?php

    $table = range(1, 9);
    shuffle($table);

    for($i=0; $i<9; $i++){

        echo '<tr id="r'.$i.'">';
         shuffle($table);

        for ($j=0; $j<9 ; $j++) { 
            echo '  <td id="r'.$i.'d'.$j.'">'.$table[$j].'</td>';
        }

        echo '</tr>';
    }

?>

</table>
于 2013-02-13T15:51:26.583 回答