Advertisement
rgruber

php mysql histogram

Dec 25th, 2022
1,482
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.02 KB | None | 0 0
  1. <?php
  2.  
  3. // Connect to MySQL
  4. $conn = mysqli_connect('host', 'username', 'password', 'database');
  5.  
  6. // Define the number of bins
  7. $bins = 10;
  8.  
  9. // Select the minimum and maximum values from the column
  10. $result = mysqli_query($conn, "SELECT MIN(col) AS min, MAX(col) AS max FROM table");
  11. $row = mysqli_fetch_assoc($result);
  12. $min = $row['min'];
  13. $max = $row['max'];
  14.  
  15. // Calculate the bin size
  16. $bin_size = ($max - $min) / $bins;
  17.  
  18. // Initialize an array to hold the bin frequencies
  19. $bin_freqs = array_fill(0, $bins, 0);
  20.  
  21. // Select the values from the column and assign them to bins
  22. $result = mysqli_query($conn, "SELECT col FROM table");
  23. while ($row = mysqli_fetch_assoc($result)) {
  24.     $col = $row['col'];
  25.     $bin = floor(($col - $min) / $bin_size);
  26.     $bin_freqs[$bin]++;
  27. }
  28.  
  29. // Print the histogram
  30. for ($i = 0; $i < $bins; $i++) {
  31.     $bin_left = $min + $i * $bin_size;
  32.     $bin_right = $bin_left + $bin_size;
  33.     echo "$bin_left - $bin_right: $bin_freqs[$i]\n";
  34. }
  35.  
  36. // Close the connection
  37. mysqli_close($conn);
  38.  
Tags: histogram
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement