It seems like this is giving me a run around. Can someone please help me here?
1) What code should I use to find the average?
2) Is there an efficient (and simple) way to find two largest values in a row of a table?
Table:
[text]+------+------+------------+-------+-------+-------+------+------+------+
| Name | Age | address | test1 | test2 | test3 | f1 | f2 | f3 |
+------+------+------------+-------+-------+-------+------+------+------+
| John | 17 | 1st street | 20 | 30 | 100 | 20.1 | 20.2 | 20.6 |
| Tina | 23 | 3rd street | 80 | | | 5.4 | 5.5 | NULL |
| Jim | 23 | 2nd street | 10 | 12 | | 3.2 | 3.5 | 0 |
+------+------+------------+-------+-------+-------+------+------+------+[/text]
Code:
Code: Select all
<?php
$conn = mysql_connect("localhost", "x", "x") or die(mysql_error());
mysql_select_db("x", $conn) or die(mysql_error());
$sql = "
SELECT name, test1, test2, test3, f1, f2, f3
From testtableR
Where name = 'Tina';
";
$result = mysql_query($sql, $conn) or die(mysql_error());
$row = mysql_fetch_array( $result );
$T_scores = array(0, 0, 0); // Do I have to do this?
$F_scores = array(0, 0);
echo "T_scores<br>";
for ($i=1;$i<=3;$i++)
{
echo $row[$i]."<br>";
$T_scores[$i-1] = $row[$i];
}
echo "<br>F_Scores<br>";
for ($i=4;$i<=6;$i++)
{
echo $row[$i]."<br>";
$F_scores[$i-4] = $row[$i];
}
echo "<br>T_Scores and F_Scores<br>";
for ($i=0;$i<3;$i++)
{
echo $T_scores[$i]." ".$F_scores[$i]."<br>";
}
// Sorting to get the get the two largest T_scores and F_Scores
sort($T_scores);
sort($F_scores);
echo "<br>Sorted arrays<br>";
for ($i=0;$i<3;$i++)
{ echo $T_scores[$i]." ".$F_scores[$i]."<br>"; }
// Take the last 2 elements--that is the two largest elements
$T = array();
$F = array();
for ($i=0;$i<2;$i++)
{
$T[$i] = $T_scores[$i+1];
$F[$i] = $F_scores[$i+1];
}
function calculate_average($arr)
{
$total = 0;
$count = count($arr); //total numbers in array
foreach ($arr as $value)
{
$total = $total + $value; // total value of array numbers
}
$average = ($total/$count); // get average value
return $average;
}
echo "<br>Averages<br>";
$F_Ave = calculate_average($F);
echo $F_Ave."<br>";
$T_Ave = calculate_average($T);
echo $T_Ave."<br>";
?>Output:
---------------------------------------
T_scores
80
F_Scores
5.4
5.5
2
T_Scores and F_Scores
80 5.4
5.5
2
Sorted arrays
2
5.4
80 5.5
Averages
5.45
40