2014-04-17 82 views
0

我有一個$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); 
+0

請發表的var_dump($競爭對手); – Steve

+0

嘗試改變這個'if($ competitor-> minSingleCareFee!= NULL){'如果(!is_null($ competitor-> minSingleCareFee)){' – Vagabond

+0

'不能幫助我們知道什麼是$競爭對手。因此,像@ user574632 –

回答

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 (!empty($competitor->minSingleCareFee)) { 
       $mm_avg_fees = $mm_avg_fees + $competitor->minSingleCareFee; 
       $data_available = $data_available + 1; 
      } 
     } 
    return $mm_avg_fees/$data_available; 
} 

echo 'The current average for single room fees in your micromarket is: ' . avg_fees($competitors, $mm_avg_fees, $data_available); 
+0

好吧,讓我檢查...有沒有辦法讓我訪問avg_fees函數之外的$ data_available變量?使用GLOBAL關鍵字的 –

+0

。參考:http://www.php.net/manual/en/language.variables.scope.php –

+0

好吧,它的工作原理,謝謝!我想知道爲什麼它不工作... –

0
  1. 它是一個類裏面呢?如果是這樣,你不能這樣做。
  2. 其他{}是不必要的。
  3. 你可以做$ data_available ++代替那裏的東西。
  4. 您正在將var作爲對象。它是什麼,一個變種或一個物體?

    $ competitor-> minSingleCareFee

,你設定的一些競爭對手是競爭對手陣中那一刻的價值。

+0

更多關於提示而不是答案。 – ponciste