gpt4 book ai didi

php - php 中 foreach 和循环语句的问题

转载 作者:行者123 更新时间:2023-11-30 00:22:20 24 4
gpt4 key购买 nike

我有许多 $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);

最佳答案

使用这个:

//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);

关于php - php 中 foreach 和循环语句的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23133411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com