Question

I am trying to import a CSV, and be able to remove columns, and only import the ones selected.

So I have an array of selected fields, and the CSV file. I can remove rows, but having problems skipping columns.

Here is what i'm using to display a table, just trying to test out removing the column. Nothing fancy here. Just need to know where to place any if statements, or anything. Tips, suggestions, samples all welcome!

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                        echo("<tr>\r\n");
                        foreach ($data as $index=>$val) {
                        echo("\t<td>$val</td>\r\n");
                        } 
                        echo("</tr>\r\n");
               } //end while

Where do i place any if statement to allow only the remainder of rows? i've tried in_array, array_diff, etc - and nothing seems to be working?

Now that i'm typing this out, should I just use PHP to delete the columns before insert? What would be best practice?

thanks jt

Was it helpful?

Solution

You can set an array containing the columns to display (in my ex 1 and 3) and use the key part of the foreach to know which is the column you are scanning:

<?
$handle = fopen("test.csv", "r");

$columns = array(1,3);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        echo("<tr>\r\n");
        foreach ($data as $index=>$val) {
                if (in_array($index+1, $columns)) {
                        echo("\t<td>$val</td>\r\n");
                }
        }
        echo("</tr>\r\n");
} //end while

?>

OTHER TIPS

Try:

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    echo("<tr>\r\n");

    foreach ($data as $index=>$val) {
        if($index != BADINDEX) {
            echo("\t<td>$val</td>\r\n");
        }   
    }
    echo("</tr>\r\n");
}

Where BADINDEX is the column number you want to get rid of (first column being 0).

Since what you get from fgetcsv are the rows and not the columns, one simply needs to filter out the desired column for every row printed, which is accomplished by checking the index in the foreach block.

This is old post but i found another way that may help someone:

$file = fopen($yourcsvfile, 'r');

    while (($result = fgetcsv($file, 1000, ",")) !== false)
    {
        $temp = array();
        $temp[] = $result[1]; // the column you want in your new array
        $temp[] = $result[2]; // the column you want in your new array
        $csv1[] = $temp;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top