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

PHP处理CSV文件上传,获取Diameter(um)列的最大值与最小值

解决CSV文件Diameter(um)列的最大值最小值获取问题

原代码仅能提取单个Diameter值,要获取该列所有数值的最大最小值,需要调整逻辑:先定位表头列索引,再遍历所有数据行收集有效数值,最后计算极值。

修改后的完整代码

$inputFileName = "your_file.csv"; // 替换为你的CSV文件路径
$fileHandle = fopen($inputFileName, "r");
if ($fileHandle === FALSE) {
    die('Error opening ' . $inputFileName);
}

$diameterIndex = null;
$diameterValues = [];

while (($currRow = fgetcsv($fileHandle)) !== FALSE) {
    // 跳过空行
    if (empty(array_filter($currRow))) {
        continue;
    }

    // 定位表头行,找到Diameter(um)的列索引
    if (trim($currRow[0]) == 'Probe ID') {
        foreach ($currRow as $index => $columnName) {
            if (trim($columnName) === 'Diameter(um)') {
                $diameterIndex = $index;
                break;
            }
        }
        // 找到表头后继续下一行,开始读取数据
        continue;
    }

    // 如果已经找到Diameter列索引,且当前行是数据行,收集数值
    if ($diameterIndex !== null) {
        $value = trim($currRow[$diameterIndex]);
        // 验证是否为有效数值
        if (is_numeric($value)) {
            $diameterValues[] = (float)$value;
        }
    }

    // 保留原代码中其他需要提取的信息逻辑
    $row = implode('|', $currRow);
    $list = explode('|', $row);
    if (trim($list[0]) == 'System Setup') {
        $fdt = $list[1];
        $prvxdt = date('Y-m-d H:i:s', strtotime($fdt));
    } elseif (trim($list[0]) == 'Probe Card Serial Number:') {
        $prvxbc = substr(trim($list[1]), 0, 10);
    }
}

// 计算最大值和最小值
$minDiameter = !empty($diameterValues) ? min($diameterValues) : null;
$maxDiameter = !empty($diameterValues) ? max($diameterValues) : null;

// 输出结果(可根据需求调整)
echo "Diameter(um)最小值: " . ($minDiameter !== null ? $minDiameter : '无有效数值') . "\n";
echo "Diameter(um)最大值: " . ($maxDiameter !== null ? $maxDiameter : '无有效数值') . "\n";

// 关闭文件
fclose($fileHandle);
$fext = '.csv';

关键修改点说明

  • 动态定位列索引:不再硬编码列位置,通过遍历表头行找到Diameter(um)对应的索引,避免列位置变动导致错误。
  • 收集有效数值:遍历所有数据行,将符合要求的数值转为浮点型存入数组,过滤无效内容。
  • 计算极值:使用PHP内置的min()和max()函数处理数值数组,同时兼容无有效数值的情况。
  • 移除不必要的分批逻辑:原代码的分批读取会中断全量数据获取,若无需分批可直接移除;若仍需分批,可在数值收集逻辑中加入分批控制。

内容的提问来源于stack exchange,提问作者StewieTwo Griffin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 17:20:05