用乐透网格粘在这里

时间:2011-03-15 12:16:46

标签: php arrays function

我有一个42 nrs的网格,我将使用rand()函数从网格中挑出数字并标记它们

到目前为止,我想出了

    <?php
    $row="";
    print ("<table border=\"1\">");
    for ($i=0; $i<6; $i++)
        {
        print ("<tr>");
            for ($j=0; $j<7; $j++)
                {
                $random = rand(1,42);
                $row += "(string)$random";
                $som = $som + 1;
                print("<th>".$som);
                }

        ("</tr>");
        }

    print ("</table>");
    print ("$rij");

 // here I'm just testing to see if I can get a list of random numbers 
 for ($i=0; $i<6; $i++){
        $randomNr = rand(1,42);
        echo "$randomNr<br/>";
        }


    ?>

我想这个想法是将rand函数中的数字与表的索引相匹配。但我真的被困在这里让表转换为arra所以我可以将索引与随机数匹配。

2 个答案:

答案 0 :(得分:1)

这将创建一个包含42个数字的网格,并标记出一个随机数字。如果你想标记更多的创建和数组,并检查只有rand变量的内容。在你原来的代码中你实际上运行了rand-function 42次,我猜这是无意的。

编辑:或者您是否需要使用随机数字填充网格?

$rand = rand(1, 42);

echo "<table>";
for($i = 1;$i <= 42; $i++) {
    if($i%7 == 1) {
        echo "<tr>";
    }
    $print = $rand == $i ? "<strong>" . $i . "</strong>" : $i;
    echo "<td>" . $print . "</td>";
    if($i%7 == 0) {
        echo "</tr>";
    }
}
echo "</table>";

答案 1 :(得分:1)

你自己的尝试可能并不太遥远。您只需生成6个随机唯一数字并与之进行比较。最简单的方法是使用range()生成一个数组,并选择array_rand()的随机数(实际上返回索引,因此您需要一些额外的代码来获取值)。然后,您只需要使用in_array()

查找当前输出的数字是否在所选数字数组中

这是一般案例的一个示例函数,它扩展了Sondre的例子。示例中的函数采用以下参数:拾取的随机数总数,网格中最小的数字,网格中的最大数字以及网格中每行的数字。该函数返回生成的HTML表源字符串。

<?php

function generateHighlightedLotteryTable ($count = 6, $min = 1, $max = 42, $perRow = 7)
{
    // Generate the picked numbers (actually we just get their indexes)
    $nums = array_rand(range($min, $max), $count);

    $output = "<table>\n";

    for ($n = $min; $n <= $max; $n++)
    {
        // get "index" of the number, i.e. $min is the first number and thus 0
        $i = $n - $min;

        if ($i % $perRow == 0)
        {
            $output .= "<tr>";
        }

        // If the current number is picked
        if (in_array($i, $nums))
        {
            $output .= "<td><strong>$n</strong></td>";
        }
        // If the current number hasn't been chosen
        else
        {
            $output .= "<td>$n</td>";
        }

        if ($i % $perRow == $perRow - 1)
        {
            $output .= "</tr>\n";
        }
    }

    // End row, if the numbers don't divide evenly among rows
    if (($n - $min) % $perRow != 0)
    {
        $output .= "</tr>\n";
    }

    $output .= "</table>";

    return $output;
}

echo generateHighlightedLotteryTable();

?>

我希望这是你想要实现的目标。