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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器