开发者

PHP, CSV columns into separate arrays

开发者 https://www.devze.com 2022-12-22 11:31 出处:网络
Basically, i want to make a system where a user can upload a CSV file and pick what columns they want to upl开发者_如何学Gooad/process

Basically, i want to make a system where a user can upload a CSV file and pick what columns they want to upl开发者_如何学Gooad/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.


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


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.


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号