简体   繁体   中英

Counting Numbers And Sorting Them

I have a question. I have created a small script which generates 37 random numbers between 0 and 36 but I want to expand it a little.

This is what I have:

<!DOCTYPE html>
<html>
<body>

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

</body>
</html>

I want to show a horizontal row of number 0 to 36 and below that I want to show how many times a number show from the previous random generator code.

Can someone help me here?

You can create an array and save the result on it.

Code

You can use 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));

OUTPUT

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
)

Try this:

<!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>

You can use a variable to store the values and then use array_keys to display the column number and arrays_values to print the values. The latter is optional.

<?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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM