0

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.

3
  • While trying to display you can filter out Commented Oct 11, 2016 at 13:27
  • well, i think you want to check on key instead of value, in_array() checks for the value, array_key_exists() checks for the key Commented Oct 11, 2016 at 13:28
  • You do not have to increase the 'i' variable. Commented Oct 11, 2016 at 13:29

1 Answer 1

2

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(...)).

Sign up to request clarification or add additional context in comments.

5 Comments

When I run this, my array is populated with null items. How do I resolve?
@michaelmcgurk: really? I will make some tests.
@michaelmcgurk: the "s" was missing in "$idsColumnsWanted"
Many thanks, @Casimir - that worked perfectly :-) I just need to now figure out how to change the numbers 0, 1, 16 to text values :-)
This is fantastic and works first time @CasimiretHippolyte

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.