簡體   English   中英

將動態生成的字符串追加到CSV行的末尾

[英]Append dynamically generated string to end of CSV line

所以我有兩個CSV:InputCSV和OutputCSV

InputCSV.csv

name     col1     col2     col3     col4     col5
john     qOJY     OHXl     vIOH     Tdnm     Z7OH
greg     YRc1     hyFB     pW8m     5LSE     Yo4r
saly     Dy4o     51Ui     tuKI     02VQ     RVgB

OutputCSV.csv

name     url
john     site.com/JcRIeyFCEl.mp4
greg     site.com/TTwF4Cue2B.mp4
saly     site.com/ouroANTtAC.mp4

所以在processor.php中,我有

    if (($csvFile = fopen("InputCSV.csv", "r")) !== false && ($resultCsv = fopen("OutputCSV.csv", 'w')) !== false) {
        while (($data = fgetcsv($csvFile)) !== false) {
            // do stuff to generate $thumbfile
            // this bit needs to use parts of $data like $data[3], $data[5] to generate $thumbfile
            // which in the end should look like $thumbfile = 'site.com/rAndOmsTRing.jpg';
        }
    $outputData = fgetcsv($resultCsv);
    $outputData[] .= $thumbfile_url; //Append to end of line. is this what I'm doing wrong? 
    fputcsv($resultCsv, $outputData);

我需要做的是在OutputCSV.csv中添加一個新列,並在每行/行的末尾附加$ thumbfile。 目前,它的作用是刪除現有的兩個列,並僅將$ thumbfile作為一個列寫入。

此腳本運行后,OutputCSV.csv需要看起來像這樣:OutputCSV.csv

name     url                         thumbfile
john     site.com/JcRIeyFCEl.mp4     site.com/snTflxaqNI.jpg
greg     site.com/TTwF4Cue2B.mp4     site.com/ELrg6vwKEr.jpg
saly     site.com/ouroANTtAC.mp4     site.com/xTjfqCEoIZ.jpg

注意:我正在使用的實際csv沒有標題。 我只將它們放在那里以幫助簡化閱讀。

為了滿足您的需求,您需要將OutputCSV.csv的數據保存在數組中,然后在同一數組中添加$ thumbfile。

在此示例中,我使用了以“,”分隔的csv文件。

    if (($csvFile = fopen("InputCSV.csv", "r")) !== false && ($resultCsv = fopen("OutputCSV.csv", 'r')) !== false) {
        while (($data = fgetcsv($csvFile,4096,",")) !== false) {
        // do stuff to generate $thumbfile
        $thumbfile[]=$data[3].$data[5].".jpg";
            }
        $x=0;
        while (($dataoutput = fgetcsv($resultCsv,4096,",")) !== false) {
            $dataotputcsv[$x]=$dataoutput;   //here is [0]=> "john" [1]=> "site.com/JcRIeyFCEl.mp4"
            array_push($dataotputcsv[$x], $thumbfile[$x]);  //here i add the $thumbfile
      //and now is [0]=> "john" [1]=> "site.com/JcRIeyFCEl.mp4" [2]=> "vIOHZ7OH.jpg"
        $x++;
        }
        $file = fopen("OutputCSV.csv", 'w'); 
        foreach($dataotputcsv as $string) {
            fputcsv($file, $string);  //save all lines to file
        }

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM