Process CSV into Array with Column Headings for Key

Process CSV Into Array With Column Headings For Key

$all_rows = array();
$header = fgetcsv($file);
while ($row = fgetcsv($file)) {
$all_rows[] = array_combine($header, $row);
}
print_r($all_rows);

PHP CSV to Array with headings and id as group-key

You can just grab the ID first an put it into the $data array as an index. Do you want to keep the ID in the data? See the comments in the code

function csv_to_array($filename='', $delimiter=',') {
if(!file_exists($filename) || !is_readable($filename))
return FALSE;

$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else{
$id = $row[0]; // grab the ID from the row / expectiong that the ID is in the first column of your CSV
//unset($row[0]); // <-- uncomment this line if you want to remove the ID from the data array
$data[$id] = array_combine($header, $row);
}

}
fclose($handle);

}
return $data;
}

How to process all or selected rows in a csv file where column headers and order are dynamic?

Let's short your function. Don't read the source twice (first with head then with sed). You can do that once. Also the whole array reading can be shorten to just IFS=',' COLUMNAMES=($(head -n1 source.csv)). Here's a shorter version:

#!/bin/bash

cat examplesource.csv |
{
IFS=',' read -r -a columnnames
while IFS=',' read -r "${columnnames[@]}"; do
echo "${firstname} ${lastname} is from ${country}"
done
}

If you want to parse both files and the same time, ie. join them, nothing simpler ;). First, let's number lines in the first file using nl -w1 -s,. Then we use join to join the files on the name of the people. Remember that join input needs to be sort-ed using proper fields. Then we sort the output with sort using the number from the first file. After that we can read all the data just like that:

# join the files, using `,` as the seaprator
# on the 3rd field from the first file and the first field from the second file
# the output should be first the fields from the first file, then the second file
# the country (field 1.4) is duplicated in 2.3, so just omiting it.
join -t, -13 -21 -o 1.1,1.2,1.3,2.2,2.3 <(
# number the lines in the first file
<examplesource.csv nl -w1 -s, |
# there is one field more, sort using the 3rd field
sort -t, -k3
) <(
# sort the second file using the first field
<examplesource2.csv sort -t, -k1
) |
# sort the output using the numbers from the first file
sort -t, -k1 -n |
# well, remove the numbers
cut -d, -f2- |
# just a normal read follows
{
# read the headers
IFS=, read -r -a names
while IFS=, read -r "${names[@]}"; do
# finally out output!
echo "${firstname} ${lastname} is from ${country} and is so many ${age} years old!"
done
}

Tested on tutorialspoint.

How to create an array from a CSV file using PHP and the fgetcsv function

Like you said in your title, fgetcsv is the way to go. It's pretty darn easy to use.

$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
print_r($line);
}
fclose($file);

You'll want to put more error checking in there in case fopen() fails, but this works to read a CSV file line by line and parse the line into an array.

CSV to Associative Array (One column as key and another as value)

With array_map you can parse the csv data and have an array to do as you wish.
Example:

// Parsing the data in csv file
$csv = array_map('str_getcsv', file('path/file.csv'));

/*At this point you already have an array with the data but
* the first row is the header row in your csv file */

//remove header row
array_shift($csv);

$data = [];

//Walk the array and add the needed data into some another array
array_walk($csv, function($row) use (&$data) {
$data[$row[3]] = $row[8];
});

And that's it.

However the data you show as an example has duplicate UPCs. You will overwrite some data if you want an array with the structure 'UPC' => 'Qty' . You can't have duplicate keys in an array.

If what you are looking for is to get the total Qty for each UPCs then you just need to add the already existing Qty with the new one if the UPC key already exists.

// Parsing the data in csv file
$csv = array_map('str_getcsv', file('file.csv'));

//remove header row
array_shift($csv);

$data = [];

//Walk the array and add the needed data into another array
array_walk($csv, function($row) use (&$data) {

$data[$row[3]] = ($data[$row[3]] ? $data[$row[3]] + (int) $row[8] : (int) $row[8]);
});

Or longer but clearer.

//Walk the array and add the needed data into another array
array_walk($csv, function($row) use (&$data) {

if(!empty($data[$row[3]]))
{
$data[$row[3]] += (int) $row[8];
}
else {
$data[$row[3]] = (int) $row[8];
}
});

PHP CSV to associative array with top row as keys and columns as value arrays

Instead of building the end array as you go along. This code reads the header row before the loop, then just reads all of the data lines into another array. It then combines each element of the header array with the matching column from the data array (using array_column() and the position of the header element)...

function readCSV($csvFile) {
$aryData = [];
$output = [];
$header = NULL;
$handle = fopen($csvFile, "r");
if($handle){
$header = fgetcsv($handle);
while ($aryData[] = fgetcsv($handle));
foreach ( $header as $key=>$label) {
$output[$label] = array_column($aryData, $key);
}
fclose($handle);
}
return $output;
}


Related Topics



Leave a reply



Submit