我想在0到36之间生成37个数字。我想在水平列表中看到这些数字。
生成两次或更多次的数字必须显示在另一个水平列表中的列表下方。
有人可以帮助我吗?
到目前为止,我有这个:
<?php
$numberOfSpins = 37;
$numberArray = array();
// Start table
echo '<table><tr>';
// print out the table headers
for ($x = 0; $x < 37; $x++) echo '<th style="font-weight:bold; color:#09f;">'.$x.'</th>';
// Fill $numberArray with random numbers
for ($i = 0; $i < $numberOfSpins; $i++)
array_push($numberArray, mt_rand(0,36));
echo '</tr><tr>';
// Count value frequency using PHP function array_count_value()
$resultArray = array_count_values($numberArray);
// Start from 0 since you are generating numbers from 0 to 36
for ($i = 0; $i < 37; $i++)
{
// array_count_values() returns an associative array (the key of
// each array item is the value it was counting and the value is the
// occurrence count; [key]->value).
if (isset($resultArray[$i]))
echo '<td>'.$resultArray[$i].'</td>';
else
echo '<td>0</td>';
}
echo '</tr></table>';
?>
答案 0 :(得分:0)
尝试这种方式:
//How many numbers the program will print
$cycles = 36;
//min random number
$minNumber = 0;
//Max random number
$maxNumber = 37;
//all numbers
$numbers = array();
//repeated numbers
$repeated_numbers = array();
//repeated numbers string, th and td
$r_numbers = "";
$th = "";
$td = "";
for ($i=1; $i < $cycles + 1; $i++) {
//get a random number
$rand_n = rand($minNumber, $maxNumber);
// create a td and th with the random number and the number index
$td .= "<td> $rand_n </td>";
$th .= "<th>Number $i </th>";
//if the new random number is already on the number array means that is repeated
// eif not, we store it in the all numbers array
if (in_array($rand_n, $numbers))
array_push($repeated_numbers, $rand_n);
else
array_push($numbers, $rand_n);
}
// we concat all the result to make a table and echo it out
$table = "<table border='1'><thead>$th</thead><tbody>$td</tbody></table>";
echo $table;
//echo the repeated numbers only
echo "<br> <br> <hr> Repeated Numbers = ";
foreach ($repeated_numbers as $num) {
echo "$num |";
}
echo "Total Repeated Numbers : " . count($repeated_numbers);
<强>更新强>
使用它来实现上述foreach以避免上一个|
for ($i = 0; $i < count($repeated_numbers); $i++) {
if ($i + 1 == count($repeated_numbers)) {
echo "$repeated_numbers[$i]";
continue;
}
echo "$repeated_numbers[$i] |";
}