PHP: Check if the value exists in csv file - php

I've a list of clients in csv file as:
Name,Credited
ABC,Y
BCD,Y
XYZ
ABC
My task is to check, if the client already exists in the list:
IF yes, check if he is already credited.
If yes, delete that name from the list.
I've started writing the code, but not sure how can I achieve my task.
//Store the file in array
$fcsv = file($files);
foreach($headers as $header) {
// Push headers to new array.
array_push($headings, strtolower(trim($header)));
}
Can someone please help!!
Thanks in advance

Loop through all the lines in the file, and use str_getcsv() to parse it as a CSV line. Then check if the first column is the client name and the second is Y.
$clients = file($files, FILE_IGNORE_NEW_LINES);
$deleted = false;
foreach ($clients as $index => $client_line) {
$split = str_getcsv($client_line);
if ($split[0] == $client) {
if (isset($split[1]) && $split[1] == 'Y') {
unset($clients[$index]);
$deleted = true;
}
break; // Stop searching after we found the client
}
}
// Rewrite the file if we deleted the client.
if ($deleted) {
file_put_contents($files, implode("\n", $clients));
}

Here's the basic implementation of searching if the name of the client exist in the given csv file.
$client = "ABC";
$fcsv = file('uploads/task.csv');
foreach ($fcsv as $key => $value) {
$temp = explode(',', $value);
if ($temp[0] == $client) {
unset($fcsv[$key]);
}
}
Each rows in csv, if you look at it using var_dump() would look like this,
"Name,Credited"
If your csv file contains of more than one rows, this line
$fcsv = file('uploads/task.csv');
will return array of rows, using a loop split the content of each rows using explode(',', $value);for you to have a data in every column of the rows.
Like in the example above you can now chose, which column you need look, to be able for you to compare where the client exist and delete.

Related

How to get value by column name in php spreadsheet-parser library?

I'm using akeneo-labs spreadsheet-parser library to extract data from xlsx file.
use Akeneo\Component\SpreadsheetParser\SpreadsheetParser;
$workbook = SpreadsheetParser::open('myfile.xlsx');
$myWorksheetIndex = $workbook->getWorksheetIndex('myworksheet');
foreach ($workbook->createRowIterator($myWorksheetIndex) as $rowIndex => $values) {
var_dump($rowIndex, $values);
}
Actually, you can get value by column index in a loop, is it possible to get value by column name instead?
maybe using another package as suggested fixes your problem.
also you can use array_column https://www.php.net/manual/en/function.array-column.php
Maybe you can do that in a spreadsheet CSV file by using PHP default function fgetcsv(), you can go throw an overview from here: https://www.php.net/manual/en/function.fgetcsv
fgetcsv — Gets line from file pointer and parse for CSV fields
First of all, save as your Xls file in CSV type then you can take your value from that CSV file by column name.
You can try this.
use Akeneo\Component\SpreadsheetParser\SpreadsheetParser;
$workbook = SpreadsheetParser::open('myfile.xlsx');
$myWorksheetIndex = $workbook->getWorksheetIndex('myworksheet');
// all columns
$columns = [];
foreach ($workbook->createRowIterator($myWorksheetIndex) as $rowIndex => $values) {
if ($rowIndex == 1) {
$columns = $values;
} else {
$datum = array_combine($columns, $values);
// get value by column name
var_dump($datum['name']);
}
}

PHP - How to delete column with no header into txt file

I have txt file where the first row contains the column names. But some rows have no title, I would like to know if there is any solution to remove those rows without column names into my txt file?
To access to my txt file:
$handleFile= fopen("/opt/lampp/htdocs/ngs/tmp/testfile.txt","r");
$dataTestFile=fgetcsv($handleFile,0,"\t");
Here's an example:
Data1;Data2;;Input;;
aaaaa;ferfs;;alpha;dfdfd;
Desired output:
Data1;Data2;Input;
aaaaa;ferfs;alpha;
First row is column names, and some of them haven't any names, I need to remove all columns which have no names.
Thanks.
I would do something like this :
<?php
$data=file_get_contents("/opt/lampp/htdocs/ngs/tmp/testfile.txt");
$array=explode("\n",$data); // putting rows in an array
$first_line=$array['0'];
$first_line_array=explode("|",$first_line);
$removed_columns=array();
foreach ($first_line_array as $key=>$value){
if(strstr(" ",$value) !== FALSE){
array_push($removed_columns,$key);
}
}
// now we know what columns to remove
$new_line='';
$new_array=array();
$new_line_array=array();
$old_line_array=array();
for($x=0;$x<count($array);$x++){
$old_line_array=explode("|",$array[$x]);
for($y=0;$y<count($old_line_array);$y++){
if(!in_array($y,$removed_columns)){
array_push($new_line_array,$old_line_array[$y]);
}
}
$new_line=join('|',$new_line_array);
array_push($new_array,$new_line);
$new_line='';
$new_line_array=array();
$old_line_array=array();
}
$new_data=join("\n",$new_array);
file_put_contents("/opt/lampp/htdocs/ngs/tmp/testfilenew.txt",$new_data)
?>
In the end you get the file (testfilenew.txt) which has the data you want
You need to 1st read the 1st row and store the column nos with empty data in an array.
Once you have the array you can use the below code to skip the columns:
$columns = array(1,3); // columns to skip
while (($data = fgetcsv($dataTestFile, 1000, "|")) !== FALSE) {
echo("<tr>\r\n");
foreach ($data as $index=>$val) {
if (!in_array($index+1, $columns)) {
echo("\t<td>$val</td>\r\n");
}
}
echo("</tr>\r\n");
} //end while

Combining two seperate arrays each with a different number of elements

I'm becoming a little frustrated with my array results. Ideally, I am creating a form maker module within my application and I am working with two different arrays to establish my database columns and excel columns. Essentially, I am using the results provided by the arrays to write directly to a php file (Excel reader file). In order to establish a difference in Excel Workbooks, I am putting forth an identifier "page2","page3" and so on within the "excel_rows" array.
//my arrays
$table_columns = array('field1','field2','field3','field4','field5'); //fields
$excel_rows = array('c1','c2','page2','c3','c4','page3','c5'); //excel columns
From here.. I go on to try to filter the array keys..
foreach(array_keys($excel_rows) as $key){
$page = array_search(strpos(trim($excel_rows[$key]),'page'),$excel_rows);
if(strpos(trim($excel_rows[$key]),'page') !== false){
$excel_row .= '$objTpl->setActiveSheetIndex('.(str_replace('page','',trim($excel_rows[$key])) -1).');<br/>'.PHP_EOL;
$table_columns[$key] = 0;
}
else {
$excel_row .= '$objTpl->getActiveSheet()->setCellValue(\''.trim($excel_rows[$key]).'\',$row[\''.trim($table_columns[$key]).'\']);<br/>'.PHP_EOL;
}
}
print $excel_row;
The result should echo out the following:
$objTpl->getActiveSheet()->setCellValue('c1', $row['field1']);
$objTpl->getActiveSheet()->setCellValue('c2', $row['field2']);
$objTpl->setActiveSheetIndex(1);<br/>
$objTpl->getActiveSheet()->setCellValue('c3', $row['field4']);
$objTpl->getActiveSheet()->setCellValue('c4', $row['field5']);
$objTpl->setActiveSheetIndex(2);
$objTpl->getActiveSheet()->setCellValue('c5', $row['']);
As one can see, I am missing 'field3' from my result and 'cs' produces and empty row rather than "field5".
I'm assuming something like array_compare or array_combine is the solution - I'm just not able to put it together.
Everything works lovely with module pardoning the array code above. Any help with this would be sincerely appreciated!
-Regards.
How it currently is I'd say you need to set an integer +1 whenever you create a new page and then subtract that integer from the key so you can get the right field.
$subkey = 0;
foreach(array_keys($excel_rows) as $key){
$fieldkey = $key - $subkey;
$page = array_search(strpos(trim($excel_rows[$key]),'page'),$excel_rows);
if(strpos(trim($excel_rows[$key]),'page') !== false){
$excel_row .= '$objTpl->setActiveSheetIndex('.(str_replace('page','',trim($excel_rows[$key])) -1).');<br/>'.PHP_EOL;
//$table_columns[$key] = 0; I'm not sure what this is supposed to do
$subkey++;
}
else {
$excel_row .= '$objTpl->getActiveSheet()->setCellValue(\''.trim($excel_rows[$key]).'\',$row[\''.trim($table_columns[$fieldkey]).'\']);<br/>'.PHP_EOL;
}
}
print $excel_row;

Fill array with contents of csv with php

I am trying to fill a array with a csv so each field is separate part of the array, when i have filled the array and echo it out it quite literally says array for every enter.
I have a feeling that once i sort the csvfull array that the sku might need to be in loop inside the main processing loop to.
$ocuk = fopen("ocuk.csv", "r");
while (($result = fgetcsv($ocuk)) !== false)
{
$csvfull[] = $result;
}
print_r ($csvfull[0][1]);
$sku="$csvfull[1]";
while (($csv = fgetcsv($ocuk)) !== FALSE)
{
if (false === empty(array_intersect($sku, $csv)))
{
code to display the results from csv that match the $sku variable
}
}
What i need it to do is csvfull array to fill with the contents of the csv such i can then call it into the variable sku to do comparison in next part of the code.
EDIT example of what i mean
csv example
data,data2,data3,data4 etc
data10,data20,data30,data40 etc
the array would then be like this
$csvfull=array() would contain the below
array("data","data2","data3","data4");
array("data10","data20","data30","data40");
then when i call csvfull[1] it display data2 then would go onto data 20 etc
$csvfull is a 2-dimensional array. The first dimension is the rows of the CSV, the second dimension is the columns. So $csvfull[1] is an array containing all the values from the second line of the file. To get the SKU, you need to drill down to the appropriate column, e.g.
foreach ($csvfull as $row) {
$sku = $row[1];
// Do something with $sku
}
If you want to get an array of all the SKUs, you can do:
$sku = array();
foreach ($csvfull as $row) {
$sku[] = $row[1];
}
try like this:
<?php
$ocuk = fopen('clientes.csv','r');
$i=0;
while(!feof($ocuk)){
$values = fgetcsv($ocuk);
if(empty($values[1] )){ // any index which is not empty to make sure that you are reading valid row.
continue;}
$csvfull[$i] = $values;
$i++;
}
print_r($csvfull);
.
fclose($ocuk);

I need to get a count of values (grouped) in a csv column

I need to get a count of the first column's values. These ID's might or might not exist in any given .csv file I receive. So I need to loop through the .csv file looking at the first column and either adding it to a holding array ($PWSs) if it doesn't exist or incrementing the count in this holding array if I've already added it.
I have the first loop using fgetcsv()..this works for cracking into the file:
$PWSs = array();
$handle2 = fopen ($uploadfileandpath,"r");
while ($field2array = fgetcsv ($handle2, 130000, ","))
{
// Here is where I would add value or increment $PWSs array
while (?)
{
if ($field2array[0] != ?)
{
// Add or increment
}
}
}
Here is actual data. The first column has IDs for Public Water Systems. I need to count them.
"00513","08/13/2009","090834311A","R","4","OR1000x6","N","N","E",,1,".73","COLILERT"
"00513","08/13/2009","090834312A","R","39","OR1000x6","N","N","E",,1,".35","COLILERT"
"00154","08/13/2009","090835401A","R","300 Falls Road","OR100016","N","N","E",,1,".10","COLILERT"
"95343","08/13/2009","090835601A","R","Room 1 Sink","OR1000x6","N","N","E",,1,,"COLILERT"
"94585","08/14/2009","090837701A","R","Kitchen","OR1000x6","N","N","E",,1,,"COLILERT"
"94704","08/14/2009","090837801A","R","Outside Tap","OR1000x6","N","N","E",,1,,"COLILERT"
"01430","08/14/2009","090838201A","R","100 Deer Park Ln OT","OR1000x6","N","N","E",,1,,"COLILERT"
"00625","08/14/2009","090839001A","R","Dano and N Rose","OR100016","N","N","E",,1,".35","COLILERT"
"00405","08/17/2009","090840301A","R","Westmont Drive","OR100016","N","N","E",,1,".28","COLILERT"
"01031","08/17/2009","090840401A","R","Unit 2 Faucet","OR100016","N","N","E",,1,,"COLILERT"
"00625","08/17/2009","090840601A","R","Luman Road","OR1000x6","N","N","E",,1,".35","COLILERT"
"00513","08/17/2009","090841001A","R","40","OR1000x6","N","N","E",,1,".18","COLILERT"
"00513","08/17/2009","090841002A","R","10","OR1000x6","N","N","E",,1,".16","COLILERT"
$fh = fopen('file.csv', 'rb');
$PWS = array();
while($row = fgetcsv($fh)) {
$PWS[$row[0]]++;
}
Basically it'll populate the PWS using the first column values as keys, and increment them as they come along. Afterwards, given your sample csv above, you'd end up with
$PWS = array(
'00513' => 4
'00154' => 1
'95343' => 1
'94585' => 1
etc...
);
function get_pws()
{
$PWSs = array();
$handle2 = fopen ($uploadfileandpath,"r");
while ($field2array = fgetcsv ($handle2, 130000, ","))
{
if(!in_array($field2array[0], $PWSs))
{
array_push($PWSs, array('key'=>$field2array[0], 'count'=>1));
}
else
{
foreach($PWSs as &$PWS)
{
if($PWS['key'] == $field2array[0])
{
++$PWS['count'];
}
}
}
}
return $PWSs;
}
I haven't actually run and tested this script, so hopefully it works and it's what you're looking for ;)
Edit: Thanks for pointing that out dq. Again, I haven't tested it (not on a machine with PHP installed atm), so hopefully it still works (if it worked in the first place) :P
You only need one while loop. Your outer while loop will stop when it hits the eof, because fgetcsv() will return FALSE.
Then just test for the column to be NULL or "" an empty string. If the column did not exist in the given array, you should use isset() to make sure it exists first in your conditional.

Categories