【问题标题】:PHP - Read CSV File & Concatenate Columns into Delimited Rows and Output into New FilePHP - 读取 CSV 文件并将列连接到分隔行并输出到新文件中
【发布时间】:2021-05-09 07:40:55
【问题描述】:

大家好,

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

例子:

12:11:00 马克你好

12:23:10 简 你好!

12:24:32 Bob 怎么了?

在输出 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 csv output concatenation


【解决方案1】:
<?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?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-17
    • 2014-11-13
    • 2014-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    相关资源
    最近更新 更多