dongnaigu2052 2015-11-13 18:27
浏览 72
已采纳

从csvRow [0]中提取部分字符串并附加到csvRow [3]

I am importing a CSV file that has the following format:

5021 2510 0600 1234 560,50,SLM
5021 2510 0600 1234 570,50,SLM
5021 2510 0600 1234 580,50,SLM

I am able to echo the data out to a 3 column table, after removing the spaces. What I am trying to do is extract from the first column number "5021251006001234560", just the segment "123456", and then append the "123456" to col[3] of the array of CSV rows. I think my comments in the code might help to explain what I am trying to achieve.

I guess what I'm after is a multidimensional array from the CSV file that looks like this:

5021251006001234560,50,SLM,123456
5021251006001234570,50,SLM,123457
5021251006001234580,50,SLM,123458

So that I can access the 4 values row by row. Here is my code so far:

$csv = array();

if (($file = fopen("uploads/" . $_FILES["file"]["name"], 'r')) === false)
{
    throw new Exception('There was an error loading the CSV file.');
}
else
{
    while (($line = fgetcsv($file, 1000)) !== false)
    {
        $csv[] = $line;
    }

    fclose($handle);
}

echo "<table>";
foreach ($csv as $rows => $row)
{
    echo "<tr>";
    foreach ($row as $col => $cell)
    {   
        $serial = '000000';
        $cell = preg_replace('/\s+/', '', $cell);

        // Check if the $cell value contains "50212510" at the start
        $findme = "50212510";   
        if (strpos($cell, $findme) === true) {
            // Get the 6 digits before the last digit
            $serial = substr($cell, 11, 6);
            // And append the 6 digits as a forth[3] value to each CSV row 
            array_push($row, $serial);
        }

        echo "<td>" . $cell . "</td>";
        if ($cell === "SLM") {
            echo "<td>" . $serial ."</td>";
        }       
    }
    echo "</tr>";
}
echo "<table>";

Any assistance would be appreciated.

展开全部

  • 写回答

1条回答 默认 最新

  • duanqiang2977 2015-11-15 02:54
    关注

    I have the answer. Like so many times, spelling out the question, realised the answer.

    foreach($array as $line)
    {
        foreach( $line as $cell )
        {
            if (substr($cell, 0, 8) === "50212510") {
                $serial = substr($cell, -7, 6);
            }           
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 KeiI中头文件找不到怎么解决
  • ¥15 QT6将音频采样数据转PCM
  • ¥15 本地安装org.Hs.eg.dby一直这样的图片报错如何解决?
  • ¥15 下面三个文件分别是OFDM波形的数据,我的思路公式和我写的成像算法代码,有没有人能帮我改一改,如何解决?
  • ¥15 Ubuntu打开gazebo模型调不出来,如何解决?
  • ¥100 有chang请一位会arm和dsp的朋友解读一个工程
  • ¥50 求代做一个阿里云百炼的小实验
  • ¥15 查询优化:A表100000行,B表2000 行,内存页大小只有20页,运行时3页,设计两个表等值连接的最简单的算法
  • ¥15 led数码显示控制(标签-流程图)
  • ¥20 为什么在复位后出现错误帧