hello,
I have a CSV file that contains order data. (id, item name, price, ship date). The first column are the column descriptions and data starts on row 2.
Right now i am able to build an array from that CSV easily.
Array
(
[0] => Array
(
[0] => ID
[1] => ITEM NAME
[2] => PRICE
[3] => SHIPDATE
)
and additionally, is this the best way to build an array that I need to manipulate data for later?
My goal is to take the CSV and show the data nicely. For example, total number of orders = 12091.30 and show a graph and how many orders were placed in january.
I have struggled with building the array correctly to read back later and build visuals.
I would use a flag to see whether I’m working on the first line of the CSV file. If I am, I’d put the column names into an array called “$colnames” with the index as the column number. Once I’m past the first line, I’d use something like
$csv[$colnames[$key]] = ...
to populate the array.
I’m not familiar with CSV handling in PHP, I wouldn’t be at all surprised to find there’s a library that does it all for you.
As for whether it’s the best way to analyse the data, I expect the answer is “it depends”. On how many rows there are, how much analysis you want to do, and probably many other things.
After you have the header names in an array variable, just use array_combine() at the point you have parsed each line of data to produce an associative array representing the data.
$input_file = 'orders.csv';
$csv = [];
// read the input file
$lines = file($input_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
// parse the csv into arrays
$lines = array_map('str_getcsv',$lines);
// get and trim the header line
$header = array_map('trim',array_shift($lines));
// loop over the data lines
foreach ($lines as $line)
{
// trim the data
$line = array_map('trim',$line);
// produce an associate array for each line
$csv[] = array_combine($header,$line);
}
echo '<pre>';
print_r($csv);