I am trying to select only certain columns from a csv using PHP. Currently I am using:
$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] );
}
}
}
Can anyone suggest any better solutions?
Edit, per OP request
Here we map column names from the first row into integers used to select those columns, rather than require the numeric identifier for the column. Untested, but I imagine it’s close.