php中的foreach和loop语句问题

时间:2014-04-17 12:41:37

标签: php mysql if-statement foreach

我有一些$competitors(这是从MySQL检索的对象数组)(比如9),我有$competitors[i]->minSingleCarefee数据,即费用数据。我想平均这个费用数据,但可能是数据集不完整,即我没有所有9个竞争对手的费用数据。因此,我通过使用if语句跟踪它,如果费用数据可用,则递增$data_available

我的问题是,似乎代码存在缺陷,因为它只返回第一个竞争对手的费用价值......我不明白为什么!当我回应时,$ 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);

2 个答案:

答案 0 :(得分:0)

  1. 是否在课堂内?如果确实如此,你不能这样做。
  2. 其他{}是不必要的。
  3. 你可以做$ data_available ++而不是那里有什么。
  4. 您正在将var视为对象。它是什么,变量或对象?

    $ competitor-> minSingleCareFee

  5. 并且你已经确定竞争对手是当时竞争对手阵容的价值。

答案 1 :(得分: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);