You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中除法操作为何导致循环跳过数据行?

棘手的PHP数据遍历异常问题

我用PHP的while循环结合mysqli_fetch_array从数据库读取4529条数据时遇到了奇怪的问题:

  • 硬编码百分比值时,循环能正常遍历所有数据;
  • 改用除法计算百分比($thisPercent = (($thisReference / $thisRAW)*100);)后,循环会跳过98条数据,最终仅输出4431条。

已做的排查:

  • 改用加法、乘法操作时循环正常,改用倒数乘法(等价于除法)也会出现跳过问题;
  • 已排除数据库中存在零值导致除零错误的情况;
  • 问题是近期修改数据录入方式后出现的,最新的124条数据中有98条会被跳过,且这些数据都是正常的非零数值(数字类型,非字符串)。

硬编码版本代码

$i = 1;
while (list($thisScoreID, $thisClassifier, $thisRAW) = mysqli_fetch_array($r, MYSQLI_NUM)){        
    // Grab the reference time that's relevant to this iteration of the loop
    $thisReference = $referenceArrayL6[$thisClassifier];
    // Calculate a percentage from scratch, using the reference time and RAW score
        $thisPercent = 50.00;
        echo "Line ".$i." of data...", PHP_EOL;
    $i++;
}

除法计算版本代码

$i = 1;
while (list($thisScoreID, $thisClassifier, $thisRAW) = mysqli_fetch_array($r, MYSQLI_NUM)){        
    // Grab the reference time that's relevant to this iteration of the loop
    $thisReference = $referenceArrayL6[$thisClassifier];
    // Calculate a percentage from scratch, using the reference time and RAW score
        $thisPercent = (($thisReference / $thisRAW)*100);
        $thisPercent = number_format($thisPercent,3);
        echo "Line ".$i." of data...", PHP_EOL;
    $i++;
}

排查建议

  1. 检查数据精度与范围:新录入的数据可能存在极小浮点数,除法运算后产生无穷大(INF)或非数值(NaN),触发隐性警告导致循环中断。建议在除法前添加日志,输出被跳过数据的$thisReference和$thisRAW具体值。
  2. 开启全量错误提示:在代码开头加入error_reporting(E_ALL); ini_set('display_errors', 1);,排查除法计算时是否有未显示的精度溢出、数值越界等警告。
  3. 验证参考数组完整性:检查新数据的$thisClassifier是否存在于$referenceArrayL6中,若不存在会导致$thisReference为null,引发运算异常。可添加判断:
    if (!isset($referenceArrayL6[$thisClassifier])) {
        echo "Missing reference for classifier: $thisClassifier at line $i\n";
        continue;
    }
    
  4. 替换数据读取方式:尝试将mysqli_fetch_array($r, MYSQLI_NUM)换成mysqli_fetch_row($r)或mysqli_fetch_assoc($r),排查是否为数组赋值模式导致的隐性问题。
  5. 移除格式化测试:先注释掉number_format调用,确认是否是格式化函数处理极端数值时干扰了循环执行。

内容的提问来源于stack exchange,提问作者Eric Brockway

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 03:33:31