gpt4 book ai didi

php - 在循环中获取数组的增量

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:41:37 25 4
gpt4 key购买 nike

我在从数据库中获取数据的 while 循环中无法正确递增变量。

这是代码:

while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
//January
if ($row['month'] ==1){
if ($row['day_range'] == '01-07') {
$val1_1 = $row['duration'];
$int1_1 = $row['intensity'];
}
elseif ($row['day_range'] == '08-14') {
$val1_2 = $row['duration'];
$int1_2 = $row['intensity'];
}
elseif ($row['day_range'] == '15-21') {
$val1_3 = $row['duration'];
$int1_3 = $row['intensity'];
}
elseif ($row['day_range'] == '22-end') {
$val1_4 = $row['duration'];
$int1_4 = $row['intensity'];
}
//Avg intensity
$int1 = ($int1_1 + $int1_2 + $int1_3 + $int1_4)/4;
}
}

所以我每个月都有这个代码。
这里的问题是有时我没有 4 个值,所以最后当我计算 AVG 时它有时是错误的,因为它总是将它除以 4

我做了什么:

我想到每次我有一个值时递增一个变量 $i,就像这样

$i = 0;
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
//January
if ($row['month'] ==1) {
if ($row['day_range'] == '01-07') {
$val1_1 = $row['duration'];
$int1_1 = $row['intensity'];
$i++;
}
elseif ($row['day_range'] == '08-14') {
$val1_2 = $row['duration'];
$int1_2 = $row['intensity'];
$i++;
}
elseif ($row['day_range'] == '15-21') {
$val1_3 = $row['duration'];
$int1_3 = $row['intensity'];
$i++;
}
elseif ($row['day_range'] == '22-end') {
$val1_4 = $row['duration'];
$int1_4 = $row['intensity'];
$i++;
}
//Avg intensity
$int1 = ($int1_1 + $int1_2 + $int1_3 + $int1_4)/$i;
}
$i = 0;
//code for next month
}

但它不起作用,我已经回应了它并且 $i 保持在 1。
我认为这是因为它逐行获取,所以它永远不会通过所有增量来达到所需的值。

请问我该怎么做?

最佳答案

// Here is an array to get the data of EACH month
$month = array();
$i = 0;
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
// This way, you will have $month[1] for January, $month[2] for February, etc.
$month[$row['month']][] = array(
"duration" => $row['duration'],
"intensity" => $row['intensity'];
);
}

// Now you get all the data, you can calculate the Avg intensity for each month
foreach ($month as $month_number => $data) {
$moy = count($month[$month_number]); // Will be 4 if you have 4 period, 3 if only 3, etc.
$sum = 0;

foreach ($data as $value) {
$sum += $value['intensity'];
}

$month[$month_number]['avg_intensity'] = $sum / $moy;
}

使用这种方法,您应该得到一个数组,其中包含您想要的所有数据,如下所示:

$month = array(
// January
1 => array(
0 => array(
'duration' => ...,
'intensity' => ...
),
1 => array(
'duration' => ...,
'intensity' => ...
),
...
'avg_intensity' => /* moy of all intensity of the month */
),
// February
2 => array(
...
),
...
);

希望对你有帮助!

编辑:

如果 Nigel Ren 的评论建议,你可以替换

$sum = 0;
foreach ($data as $value) {
$sum += $value['intensity'];
}

通过

$sum = array_sum(array_column($data, "intensity"));

关于php - 在循环中获取数组的增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50580692/

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