dongnaigu2052 2015-11-14 02: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 10: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 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog