michaelmcgurk michaelmcgurk - 11 days ago 5
PHP Question

PHP read CSV & ignore certain columns

I have a simple PHP script that reads a CSV file and generates an array from this:

<?php
$file = fopen('food.csv', 'r');
$allfile = [];
$idsColumnsWanted = array(0,1,16);
while (($line = fgetcsv($file)) !== FALSE) {

$i = 0;

foreach ($line as $i => $cell) {
if (!in_array($i, $idsColumnsWanted)) {
continue;
}
$allfile[] = $line;
$i++;
}

}
fclose($file);
?>


I'd like to display just the data in columns 0, 1 & 16.

I have made an attempt above, but it still outputs the entire CSV.

Answer

You can do it with array_intersect_key:

$file = fopen('food.csv', 'r');
$allfile = [];

$idsColumnsWanted = array_flip([0, 1, 16]);

while (false !== $fields = fgetcsv($file)) {
    $allfile[] = array_intersect_key($fields, $idsColumnsWanted);
}

fclose($file);

Note: if you don't want to preserve the column numbers as keys in your result array, use array_values(array_intersect_key(...)).

Comments