Mega Code Archive

 
Categories / Php / MySQL Database
 

Finds the median in an array of numbers - Can be used with a MySql

database column read into an array // sloppy but functional way to find the median in an ordered list // connect to database $link = mysql_connect("host","dbase","password"); $db = mysql_select_db("dbase", $link); // select and retreive data $sql = "SELECT * FROM table_name"; $sql_result = mysql_query($sql,$link); $i=0; while ($row = mysql_fetch_array($sql_result)) { // load array with data from table $test_data[] = $row["test_data"]; $i = $i + 1; } // sort the array rsort($test_data); for ( $count = 0; $count<$i; $count++) echo "$test_data[$count] <br>"; mysql_free_result($sql_result); $oe_value = count($test_data); if ($oe_value % 2 == 0 ) { $position = 1; } else { $position = 2; } if ($position == 2 ) { $median = $test_data[(count($test_data)/2)]; } else { $median= (($test_data[(count($test_data)/2)-1]) + ($test_data[(count($test_data)/2)]))/2; } // $median will either be the middle value in the array if the count is odd // or the average of the center two numbers if the count is even