我使用以下代码来查找平均值和频率,但直接指定值 我需要的是找到数据库值的平均值和频率。 我在这个项目中使用codeigniter希望有人可以帮助我。 谢谢。
<script>
var numberArray=[5,5,1,1], thisTotal=0,thisMean=0;
// add elements of array together
for(var i=0;i<numberArray.length;i++)
{
thisTotal+=numberArray[i];}
// calculate average
thisMean=(thisTotal/numberArray.length);
thisFrequency=(numberArray.length);
// display result
alert(thisMean);
alert(thisFrequency);
</script>
同样的逻辑可以在PHP中使用
你可以有array(1,2,3,4)并使用for或foreach循环遍历它。长度方法在 PHP 中称为 count(),因此您必须在 for 循环中调用 count($yourArray)。
您可以使用foreach($yourArray as $key => $value)
因此$key就像在循环中一样使用$i。
PHP 还提供了本机 array_sum() 函数,该函数对其中的所有值求和。
<?php
$numberArray=array(5,5,1,1); // predefined array
$thisTotal=0;
$thisMean=0;
/*
* Array from database assuming you have $mysqli object
*/
$sql = "SELECT col1, col2, col3 FROM table1";
$result = $mysqli->query($sql);
while ($row = $result->fetch_assoc()) {
$arrayFromDataBase[] = $row;
}
/*
* numberArray.length (count)
* Since you use it three times, use the variable assigned to it
* instead of typing each time numberArray.length /count($numberArray)/
*/
$thisFrequency=count($numberArray); //change to count($arrayFromDataBase) in order to have array from db;
// the same logic
for ($i = 0; $i < $thisFrequency; $i++) {
$thisTotal+=$numberArray[$i];
}
// If using associative fetching from database, you would really need foreach()
foreach ($numberArray as $key => $value) {
$thisTotal+=$numberArray[$key];
}
/*
* or a better logic
* use one the three provided ways, depending on your needs
*/
$total = array_sum($numberArray);
$thisMean=($thisTotal/$thisFrequency);
echo $thisTotal . "<br />"; // echo $total will give the same result, array_sum() saves your entire loop
echo $thisMean . "<br />";
echo $thisFrequency . "<br />";
?>
阅读代码中的注释,因为如果您将其整体粘贴,它不会给您所需的结果,提供了所有方法,并且变量将具有三重值。根据您的需求进行切割。