繁体   English   中英

PHP - 读取 CSV 文件并将列连接到分隔行和 Output 到新文件中

[英]PHP - Read CSV File & Concatenate Columns into Delimited Rows and Output into New File

大家好,

试图通过自动化我的一些工作来改进我的 PHP 并减少繁琐的工作量。 我正在尝试编写一个 PHP 文件,该文件采用 CSV 并将列转换为分隔行。

例子:

12:11:00 马克你好

12:23:10 简 你好!

12:24:32 Bob 怎么了?

在 output CSV 中,应该是一行三列,如下所示[分隔符为 |||]:

12:11:00|||12:23:10|||12:24:32,马克|||简|||鲍勃,你好|||你好?|||怎么了?

我在这里看到了类似的代码,但它把所有的代码连接成一个块,我试图修改它以使其分成三列。

我不是这段代码的作者,因为我从 Stack Exchange 上的一篇文章中抓取了它,并试图为我的用例修改它。 如果有人可以帮助我,我将不胜感激!

<?php

$rows = [];

$file = fopen("test.csv", "r"); // open your file

while (!feof($file)) { // read file till the end

    $row = fgetcsv($file); // get current row as an array of elements

    if (!empty($row)) { // check that it's not the empty row

        array_push($rows, $row); // store row in array
    }
}

fclose($file);

for ($r1 = 0; $r1 < count($rows); $r1++) {
echo $rows[$r1][0] . '_' . PHP_EOL;}


for ($r2 = 0; $r2 < count($rows); $r2++) {
echo $rows[$r2][1] . '_' . PHP_EOL; }


for ($r3 = 0; $r3 < count($rows); $r3++) {
echo $rows[$r3][2] . PHP_EOL;}
<?php

$myfile = fopen("test.csv", "r") or die("Unable to open file!");
$content = fread($myfile, filesize("test.csv"));
fclose($myfile);

$times = $names = $texts = [];
foreach (explode("\n", $content) as $line) {
    $words = explode(' ', $line); // separate line by spaces

    $times[] = $words[0]; // first string
    $names[] = $words[1]; // second string
    $texts[] = implode(' ', array_splice($words, 2)); // all remaining strings
}

$output = implode('|||', $times).','.implode('|||', $names).','.implode('|||', $texts);

echo $output."\n";

->

12:11:00|||12:23:10|||12:24:32,Mark|||Jane|||Bob,Hello|||Hi there!|||What's up?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM