CSV通过PHP重复第一个条目

时间:2018-04-27 03:00:40

标签: php csv

我有以下代码

<?php
if (($handle = fopen("cat.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {           
        if (isset($data[0])) {
            echo $data[0] . "<br>\n";
        }
    }
    fclose($handle);
}
?>

并打印CSV文件中的类别,如下所示:

Main Category

Sub Category1

Sub Category2

Sub Category3

Sub Category4

我需要实现的是让主类别再次添加代码。我该如何管理?

Main Category Sub Category1

Main Category Sub Category2 

Main Category Sub Category3

Main Category Sub Category4

我一直在检查过去几个小时的每一个细节,但我遗漏了一些东西。任何帮助表示赞赏

1 个答案:

答案 0 :(得分:0)

假设您的cat.csv文件布局如下:

Main Category,Sub Category1,Sub Category2,Sub Category3,Sub Category4

以下代码应该可以解决问题。如果您将每一行的主要类别设为第一列,则会正确打印出来。

<?php
    // Open your CSV File.
    $FileHandle = FOpen("cat.csv", "r");
    // Initiate a counter to count the ROWS of the file.
    $RowCtr = 1;
    // Create an empty variable to hold your prefix ("Main Category").
    $Prefix = "";
    // Verify the file is open.
    If ($FileHandle !== FALSE) {
        // Loop through the CSV file.
        While (($Data = FGetCSV($FileHandle, 1000, ",")) !== FALSE) {
            // Count the number of Columns.
            $ColCtr = COUNT($Data);
            // Add another row the the ROW counter.
            $RowCtr++;
            // Loop through each column.
            For ($c = 0; $c < $ColCtr; $c++) {
                // If first iteration, save the value to the prefix for later use.
                If ($c == 0) {
                    $Prefix = $Data[$c];
                    // Echo $Data[$c] . "<br />";   // Uncomment this line to print the Main Category by itself first.
                } Else {
                    // Echo out the prefix with the new values.
                    if (!Empty($Data[$c])) {
                    Echo $Prefix . " " . $Data[$c] . "<br />";
                    }   
                }
            }
        }
        // Close the file.
        FClose($FileHandle);
    } Else {
        // Handle case if file cannot be opened.
    }
?>

这将打印出来

Main Category Sub Category1
Main Category Sub Category2
Main Category Sub Category3
Main Category Sub Category4

如果您的CSV如下所示

Main Category,Sub Category1,Sub Category2,Sub Category3,Sub Category4
Main Category2,Sub Category5,Sub Category6,Sub Category7,Sub Category8

它会打印出来

Main Category Sub Category1
Main Category Sub Category2
Main Category Sub Category3
Main Category Sub Category4
Main Category2 Sub Category5
Main Category2 Sub Category6
Main Category2 Sub Category7
Main Category2 Sub Category8

我希望这有帮助!