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

时间:2015-11-14 02:27:21

标签: php arrays csv

我正在导入具有以下格式的CSV文件:

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

删除空格后,我能够将数据回显到3列表。我想要做的是从第一列编号" 5021251006001234560"中提取,只是段" 123456",然后追加" 123456"到CSV行数组的col [3]。我认为我在代码中的评论可能有助于解释我想要实现的目标。

我想我之后的内容是CSV文件中的多维数组,如下所示:

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

这样我就可以逐行访问4个值。到目前为止,这是我的代码:

$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>";

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

我有答案。像很多次一样,拼出问题,实现了答案。

foreach($array as $line)
{
    foreach( $line as $cell )
    {
        if (substr($cell, 0, 8) === "50212510") {
            $serial = substr($cell, -7, 6);
        }           
    }
}