数数并排序

Counting Numbers And Sorting Them

我有一个问题。我创建了一个小脚本,它生成 0 到 36 之间的 37 个随机数,但我想稍微扩展一下。

这是我的:

<!DOCTYPE html>
<html>
<body>

<?php  
for ($x = 1; $x <= 37; $x++) {
  echo(mt_rand(0,36) . "<br>");
}
?>

</body>
</html>

我想显示数字 0 到 36 的水平行,我想显示数字从之前的随机生成器代码中显示了多少次。

有人可以帮我吗?

您可以创建一个数组并将结果保存在上面。

代码

您可以使用array_count_values

$random_numbers = array();
echo 'Random Numbers: ';
for ($x = 1; $x <= 37; $x++) {
    $random_numbers[] = mt_rand(0,36);
}
print_r(array_count_values($random_numbers));

输出

Array
(
    [21] => 1
    [22] => 1
    [15] => 1
    [6] => 2
    [13] => 2
    [24] => 2
    [35] => 3
    [0] => 1
    [3] => 2
    [32] => 1
    [19] => 2
    [9] => 2
    [28] => 2
    [29] => 1
    [33] => 1
    [11] => 1
    [2] => 3
    [25] => 1
    [10] => 2
    [4] => 1
    [30] => 1
    [20] => 1
    [27] => 1
    [26] => 1
    [12] => 1
)

您可以使用变量存储值,然后使用 array_keys to display the column number and arrays_values 打印值。后者是可选的。

<?php

$numbers = [];

for($x = 1; $x <= 10; $x++) {
    $numbers[$x] = mt_rand(0,36);
}

echo implode("\t | \t", array_keys($numbers));
echo PHP_EOL;
echo implode("\t | \t", $numbers);

试试这个:

<!DOCTYPE html>
<html>
<body>
<?php

    $numberOfSpins = 10000;
    $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>';
?>
</body>
</html>