PHP中可以使用相同的逻辑
您可以拥有 array(1,2,3,4) 并使用 for 或 foreach 循环遍历它。length 方法在 PHP 中称为 count(),因此您必须在 for 循环中调用 count($yourArray)。
您可以foreach($yourArray as $key => $value)
在循环中使用 $key as $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 />";
?>
阅读代码中的注释,因为如果您将其全部粘贴,它不会给您想要的结果,提供了所有方式,并且变量将具有三重值。剪裁它以满足您的需求。