views:

321

answers:

3

Basically, i want to make a system where a user can upload a CSV file and pick what columns they want to upload/process

I can do this fine by using fopen and foreach, but since the number of the column may vary from CSV to CSV....

i can store the picked columns in an array, eg picked[]= "1,2,4"; //from 1,2,3,4 columns comma separated or anyway i want.

but how can i use something like list(1,2,4) = explode("," , theData[]);

where i can load 1,2,4, in there dynamically, or even 1,2,3,4 and then i can ignore 3.

A: 

well the csv is sort of a 2 dimensional array as you got the row index and column index.

First you will have to split your line breaks (\n) to split everything in seperate rows. Then each row has to be seperated by comma. For the first row you will have the column names.

All this can easily be coded yourself...

Or you could use the fgetcsv function

Function gets explained on: http://php.net/manual/en/function.fgetcsv.php

Luuk van Rens
A: 

You can unset the columns you don't need from each row:

$theData = array(
    array( 'col1', 'col2', 'col3', 'col4', 'col5' ),
    array( 'col1', 'col2', 'col3', 'col4', 'col5' ),
    array( 'col1', 'col2', 'col3', 'col4', 'col5' )
    );
$picked = '1, 3, 5';

$totalColumns = count( $theData[0] );
$columns = explode( ',', $picked );
foreach( $theData as $k => &$thisData ) {
    for( $x = 1; $x < $totalColumns + 1; $x++ ) {
        if( ! in_array( $x, $columns ) ) {
            unset( $thisData[$x - 1] );
        }
    }
}

Watch out for the 0-index adjustments in the for loop and the unset - this is because you have used column numbers that are non 0-indexed in your example.

Andy
Antigirl
standard foreach loop with the variable being passed by reference - usually PHP creates a copy of the array to foreach through, and using a reference (i.e. a link to the actual variable) we can then unset $thisData and have that variable removed from $theData - hope that makes sense! If not, check out http://www.php.net/manual/en/language.references.php
Andy
A: 

You could use array_intersect_key(): "returns an array containing all the entries of array1 which have keys that are present in all the arguments."

http://www.php.net/manual/en/function.array-intersect-key.php

So first you need to process the data line by line, e.g. to an array that looks like

$data[column] = array(entries):

Example:

$data = array(
  1 => array (
    entry1,
    entry2,
    etc
  ),
  2 => etc
);

Then you show the user which columns there are, the user selects the columns he likes to use, e.g.:

$selected = array(1,2,4);

Then do an intersect to get an array with the selected columns:

 $use = array_intersect_key($data, $selected);
Alec