dongsong73032 2014-05-14 17:44
浏览 17
已采纳

使用PHP从csv矩阵中选择特定值

I have been going round in circles with this and I'm hoping someone can help.

I have a .csv file containing data, example:

Weight, 10, 20, 30, 40

product1, 1, 2, 3, 4

product2, 2, 4, 6, 8

product3, 3, 6, 9, 12

What I need to do, using PHP, is select the value from the matrix where the row is "product2" and the number in that row corresponds with the nearest rounded match to a Weight of 27. The result should therefore be 6.

I've tried adding the csv rows to an array using fgetcsv and looping through to get the line where the first array item = product2, but I can't cross reference it with the Weight values from line 1.

I appreciate this csv is effectively upside down but this is the easiest way to manage it.

I can post some code I've tried so if it helps but, to be honest, it's all a bit of a mess so I was hoping someone could point me in the right direction with some working code.

Any help is appreciated! Thanks.

  • 写回答

2条回答 默认 最新

  • dptdb84606 2014-05-14 18:03
    关注

    You should define what the nearest rounded match is. For 24 it should look the value for 20? I think as I understand what for you use it for 24 it should also be 30 otherwise you should define if round should be defined for a half of weights (first column) or not.

    There is sample code that works as I think it should, so for 24 it will also choose 30

    PHP file:
    
    
    <?php
    
    $name = 'product2';
    $weight = 24;
    
    $lines = explode("
    ", file_get_contents("test.csv"));
    
    $found= '';
    
    $foundCost = false;
    
    foreach ($lines as $line) {
      if (strpos($line,$name.',') === 0) {
         $found = $line;
         break;
      }
    }
    
    
    
    
    
    
    if ($found != '') {
        $found = explode(',', $found);
        $weights = explode(',',$lines[0]);
    
        $index = false;
    
        for ($i=1; $i<count($weights); ++$i) {
           if ($weights[$i] >= $weight)  {
               $index = $i;
               break;
           }       
        }
        if ($index !== false) {
            $foundCost = $found[$index];    
        }
    
    }
    
    if ($foundCost !== false) {
    
        echo "found ".$foundCost;
    }
    

    CSV file (I assumed there are no space after , as in ordinary CS file):

    Weight,10,20,30,40
    product1,1,2,3,4
    product2,2,4,6,8
    product3,3,6,9,12
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大