我有一個$competitors
(這是從MySQL檢索的對象數組)(例如9),我有$competitors[i]->minSingleCarefee
數據,即費用數據。我想對這些費用數據進行平均處理,但可能數據集並不完整,即我沒有9個競爭對手的費用數據。因此,如果費用數據可用,我通過使用if語句並且遞增$data_available
來跟蹤該數據。問題與foreach和循環語句在php
我的問題是,它似乎代碼有缺陷,因爲它只返回第一個競爭對手的費用價值......我不知道爲什麼!同時$ data_available在我回顯時總是最終爲0。
//declaring variables
$mm_avg_fees = 0;
$data_available = 0;
//function to calculate average fees
function avg_fees($competitors, $mm_avg_fees, $data_available){
foreach ($competitors as $competitor) {
//impose condition to increment data_available
//only if there is data in the minSingleCareFee column for the $competitor
if ($competitor->minSingleCareFee != NULL) {
$mm_avg_fees = $mm_avg_fees + $competitor->minSingleCareFee;
$data_available = $data_available + 1;
} else {}
}
return $mm_avg_fees/$data_available;
}
echo echo 'The current average for single room fees in your micromarket is: ' . avg_fees($competitors, $mm_avg_fees, $data_available);
請發表的var_dump($競爭對手); – Steve
嘗試改變這個'if($ competitor-> minSingleCareFee!= NULL){'如果(!is_null($ competitor-> minSingleCareFee)){' – Vagabond
'不能幫助我們知道什麼是$競爭對手。因此,像@ user574632 –