Count values in CSV - php

The .csv file:
question1,question2,question3,question4,question5,question6,question7,question8,question9,question10
yes,response,response,response,response,response,response,response,response,response
yes,response2,response2,response2,response2,response2,response2,response2,response2,response2
no,response3,response3,response3,response3,response3,response3,response3,response3,response3
I want to get this result in php.
$question = "the_question_goes_here"
question1
yes = 2
no = 1
The code must find the unique responses for each question and count how many of each.
Can anyone help?

str_getcsv() can be used to get a csv string as an array.
Using this you can write a loop over the array which counts up values (in pseudocode):
counts = array;
//Loop over each row
for(row in csvrows){
for(cell in row){
counts[rowHeader][cellValue] = counts[rowHeader][cellValue]+1;
}
}

This should do the trick reading the file contents into PHP
$data= array();
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
foreach ($data as $position => $value) {
if($row == 1) {
$data[$position]['question'] = $value;
$data[$position]['yes'] = 0;
$data[$position]['no'] = 0;
continue;
}
if ($value == 'yes') {
$data[$position]['yes'] = $data[$position]['yes'] + 1
} elseif ($value == 'no') {
$data[$position]['no'] = $data[$position]['no'] + 1
}
}
$row++;
}
fclose($handle);
}
This will return a array which you can read like this
Array value
'question' key holding text
'yes' key holding numOf yes
'no'key holding numOf no

Related

Gravity forms: exporting two forms of entries data to one CSV file

I'm wondering if I can export two deferent forms entries based on the submitter id but with a specific concept,
The concept is:
If the entry title from the first form == some entry field of the other form, let's show these two entries in the exported data in one row, and so on, something like array_map in php.
I hope that you got the idea, any help to do that?
Thanks a lot,
Magdi
Use These Codes:
(first code returns data from csv file into an array)
(second code gets data from an array and save into a csv file)
function csvExporter($path) {
$csv = array();
$row = 1;
if (($handle = fopen($path, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$csv[str_pad($row,4,0,STR_PAD_LEFT)] = array();
for ($c = 0; $c < $num; $c++) {
$csv[str_pad($row,4,0,STR_PAD_LEFT)][$c] = $data[$c];
}
$row++;
}
fclose($handle);
}
return $csv;
}
function csvImporter($path,$array) {
$csvFile = fopen($path,'w+');
foreach ($array as $rows) {
$eachRow = '[';
foreach ($rows as $columns) {
$eachRow .= '\'' . trim($columns,'\'') .'\',';
}
$eachRow .= ']' . PHP_EOL;
}
fclose($csvFile);
}

PHP CSV duplicate values

I've got a csv file which contains product datas and prices from two distributors.
There are 67 keys in this file.
Now I want to search all EANs in this file which are twice available and then get the cheapest price.
After that delete the other higher price product line.
The CSV has a key for my merchant.
I made a test csv for easier view:
artno;name;ean;price;merchant
1;ipad;1654213154;499.00;merchant1
809;ipad;1654213154;439.00;merchant2
23;iphone;16777713154;899.00;merchant2
90;iphone;16777713154;799.00;merchant1
After the script runs through, the csv should look like (writing to new file):
artno;name;ean;price;merchant
809;ipad;1654213154;439.00;merchant2
90;iphone;16777713154;799.00;merchant1
I played around with fgetcsv, looping through the csv is not a problem, but how I can search for the ean in key 2?
$filename = './test.csv';
$file = fopen($filename, 'r');
$fileline = 1;
while (($data = fgetcsv($file, 0, ";")) !== FALSE) {
if($fileline == "1"){ $fileline++; continue; }
$search = $data[2];
$lines = file('./test.csv');
$line_number = false;
$count = 0;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== FALSE) ? $key : $line_number;
$count++;
}
if($count > 2){
echo "<pre>",print_r(str_getcsv($lines[$line_number], ";")),"</pre>";
}
}
I think this is what you are looking for:
<?php
$filename = './test.csv';
$file = fopen($filename, 'r');
$lines = file('./test.csv');
$headerArr = str_getcsv($lines[0], ";");
$finalrawData = [];
$cheapeastPriceByProduct = [];
$dataCounter = 0;
while (($data = fgetcsv($file, 0, ";")) !== FALSE) {
if($dataCounter > 0) {
$raw = str_getcsv($lines[$dataCounter], ";");
$tempArr = [];
foreach( $raw as $key => $val) {
$tempArr[$headerArr[$key]] = $val;
}
$finalrawData[] = $tempArr;
}
$dataCounter++;
}
foreach($finalrawData as $idx => $dataRow ) {
if(!isset($cheapeastPriceByProduct[$dataRow['name']])) {
$cheapeastPriceByProduct[$dataRow['name']] = $dataRow;
}
else {
if(((int)$dataRow['price'])< ((int)$cheapeastPriceByProduct[$dataRow['name']]['price'])) {
$cheapeastPriceByProduct[$dataRow['name']] = $dataRow;
}
}
}
echo "<pre>";
print_r($finalrawData);
print_r($cheapeastPriceByProduct);
I just added $finalData data array to store the parsed data and associated all rows with their header key counterpart then you can compare and filter data based on your criteria.

PHP beginner - issues with associative arrays

I'm trying to take a file of id numbers and find the names associated with those numbers from a different file and print a csv in the form id,name.
The Def.csv file is in the form
1;128;34;64;Uppland,
2;0;36;128;Östergötland,
3;128;38;192;Småland,
WIth the first number being the ID and the last field the name.
The IDs.csv is just IDs in no specific order with a comma and new line. ie.
12, \n
Here's the (updated, bad) script:
<?php
$ID;
$names;
$both = array();
$row = 0;
echo ("1\n");
if (($handle = fopen("IDs.csv", "r+")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$ID[$row] = $data[0];
$row++;
//print_r($ID);
}
}
print_r($ID);
fclose($handle);
if (($handle = fopen("Defs.csv", "r+")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$Names = $data[4];
// DEBUG, works// echo "$Names";
}
}
fclose($handle);
for ($c = 0; $c < $row; $c++)
{
$Both[$ID[$c]] = $Names[$ID[$c]];
}
foreach ($Both as $key => $value)
{
echo "$key,$value\n";
}
?>
This is my current output
Array
(
[0] => 2
[1] => 3
[2] => 1
)
2,t
3,l
1,u
for the small test case here it should be 2,Östergötland 3,Småland and 1,Uppland

unable to write csv from array

I read most of the discussions about my problem but I do not find a solution.
So, I have a .csv file from which I read, extract all the content and populate a multidimensional array. That is the code I wrote to do that:
if (($handle = fopen("dateRegion.csv", "r")) !== FALSE) {
# Set the parent multidimensional array key to 0.
$pr = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
# Count the total keys in the row.
$count = count($data);
# Populate the multidimensional array.
for ($x = 0; $x < $count; $x++) {
$brim[$pr][$x] = $data[$x];
}
$pr++;
}
fclose($handle);
}
After that, I extract the element I need and put it into another array. That array will be the content of the new .csv file.
This is the code:
$parserCsv = array();
$dip=1;
do {
$region = $brim[$dip][7];
$sex = $brim[$dip][8];
$frequency = $brim[$dip][9];
$value = $brim[$dip][10];
$parserCsv[] = array($region, $sex, $frequency, $value);
$dip++;
} while($dip <= 6336);
This is the "var_dump()" of the array:
Array(
[0] => Piemonte
[1] => maschi
[2] => 2005
[3] => 16.972)
etc.
I tried to put the content of the array $parserCsv using the method fputcsv(), with that script:
$fp = fopen('csvExtract.csv', 'w');
foreach ($parserCsv as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
but it did not work. The content of the file csvExtract.csv is blank. I do not understand my mistake, I tried other solution like create the array $parserCsv like:
$parserCsv = array(
array($region), array($sex), array($frequency), array($value));
and nothing change. Does anyone have some advise?
EDIT: Edited the code with the solution suggested by mkjasinski! The code is working now.
Thanks for all the replies.
Brus
Try this:
if (($handle = fopen("dateRegion.csv", "r")) !== FALSE) {
# Set the parent multidimensional array key to 0.
$pr = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
# Count the total keys in the row.
$count = count($data);
# Populate the multidimensional array.
for ($x = 0; $x < $count; $x++) {
$brim[$pr][$x] = $data[$x];
}
$pr++;
}
fclose($handle);
}
and this:
$parserCsv = array();
$dip=1;
do {
$region = $brim[$dip][7];
$sex = $brim[$dip][8];
$frequency = $brim[$dip][9];
$value = $brim[$dip][10];
$parserCsv[] = array($region, $sex, $frequency, $value);
$dip++;
} while($dip <= 6336);
and save:
$fp = fopen('csvExtract.csv', 'w');
foreach ($parserCsv as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
are you getting some errors?
Is the file open in some other software? (like MS Excel?)
Following code enters 4 records in CSV
$parserCsv = array(
array('Piemonte'),
array('maschi'),
array(2005),
array(16.972)
);
$fp = fopen('blah.csv', 'w');
foreach($parserCsv as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);

CSV to Json with header row as key

I would like to convert a CSV to Json, use the header row as a key, and each line as object. How do I go about doing this?
----------------------------------CSV---------------------------------
InvKey,DocNum,CardCode
11704,1611704,BENV1072
11703,1611703,BENV1073
---------------------------------PHP-----------------------------------
if (($handle = fopen('upload/BEN-new.csv'. '', "r")) !== FALSE) {
while (($row_array = fgetcsv($handle, 1024, ","))) {
while ($val != '') {
foreach ($row_array as $key => $val) {
$row_array[] = $val;
}
}
$complete[] = $row_array;
}
fclose($handle);
}
echo json_encode($complete);
Just read the first line separately and merge it into every row:
if (($handle = fopen('upload/BEN-new.csv', 'r')) === false) {
die('Error opening file');
}
$headers = fgetcsv($handle, 1024, ',');
$complete = array();
while ($row = fgetcsv($handle, 1024, ',')) {
$complete[] = array_combine($headers, $row);
}
fclose($handle);
echo json_encode($complete);
I find myself converting csv strings to arrays or objects every few months.
I created a class because I'm lazy and dont like copy/pasting code.
This class will convert a csv string to custom class objects:
Convert csv string to arrays or objects in PHP
$feed="https://gist.githubusercontent.com/devfaysal/9143ca22afcbf252d521f5bf2bdc6194/raw/ec46f6c2017325345e7df2483d8829231049bce8/data.csv";
//Read the csv and return as array
$data = array_map('str_getcsv', file($feed));
//Get the first raw as the key
$keys = array_shift($data);
//Add label to each value
$newArray = array_map(function($values) use ($keys){
return array_combine($keys, $values);
}, $data);
// Print it out as JSON
header('Content-Type: application/json');
echo json_encode($newArray);
Main gist:
https://gist.github.com/devfaysal/9143ca22afcbf252d521f5bf2bdc6194
For those who'd like things spelled out a little more + some room to further parse any row / column without additional loops:
function csv_to_json_byheader($filename){
$json = array();
if (($handle = fopen($filename, "r")) !== FALSE) {
$rownum = 0;
$header = array();
while (($row = fgetcsv($handle, 1024, ",")) !== FALSE) {
if ($rownum === 0) {
for($i=0; $i < count($row); $i++){
// maybe you want to strip special characters or merge duplicate columns here?
$header[$i] = trim($row[$i]);
}
} else {
if (count($row) === count($header)) {
$rowJson = array();
foreach($header as $i=>$head) {
// maybe handle special row/cell parsing here, per column header
$rowJson[$head] = $row[$i];
}
array_push($json, $rowJson);
}
}
$rownum++;
}
fclose($handle);
}
return $json;
}

Categories