Search code examples
phparrayscsvfpdf

PHP - Getting certain columns from csv file into array


I am really struggling to work out how to turn certain columns of data from a csv file into an array. At the moment I can convert the whole thing into an array using:

$csv = array();

$lines = file('../data/StaffData.csv', FILE_IGNORE_NEW_LINES);

foreach ($lines as $key => $value)
{
    $csv[$key] = str_getcsv($value);
}

But is there a way to only get certain columns from the array? Such as columns 1 and 2, or 1 to 4? etc.

The goal is to do this so I can put certain data into a table with FPDF. Which I am also struggling with :/

-So if anyone knows how to quickly put a nice looking table into FPDF let me know please. I am trying to use BasicTable function from the site, but my table is going off the page and doesn't look great. Its the first time I have used it, and it is going pretty terribly.

I know this is kind of 2 questions. But the first one (in the title) is the main one to start with. Thanks


Solution

  • str_getcsv() parses a single row, and you simply need to extract data from the row.

    $csv = array();
    
    $lines = file('../data/StaffData.csv', FILE_IGNORE_NEW_LINES);
    
    foreach ($lines as $key => $value)
    {
        $row = str_getcsv($value);
        $csv[$key] = array($row[0], $row[1], ..., $row[n]);
    }
    

    Where you specify the column numbers you want in array($row[0], $row[1], ..., $row[n]);