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

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

Related

How to check the value is present inside an array and insert the value into database using PHP

I need some help. I need to insert the the value if its present inside the user input array using PHP and MySQL. I am explaining my table below.
db_images:
id image subcat_id
Here I need to insert into above table as the following json array value.
$subcat=array(array("id"=>63),array("id"=>64));
$imageArr=array(array("image"=>"abc.png","id"=>63));
Here I need to match both array if any value from $subcat array is present inside the second (i.e-$imageArr) array then the resepective image will insert into the table and if not present the the blank image value will insert with the respective subcat_id . Please help.
For every element in the subcat array, you can iterate on the imageArr and check if the ids match (nested loop), like this:
foreach($subcat as $s) {
$flag = false;
foreach($imageArr as $i) {
if ($s['id'] == $i['id']) {
// insert ($i['image'], $s['id']) into db
$flag = true;
break;
}
}
if ($flag == false) {
// insert $s['id'] into db
}
}
Hi you can even do in the following way with the help of array_column and in_array with loop reduced.
<?php
$subcat=array(array("id"=>63),array("id"=>64));
$imageArr=array(array("image"=>"abc.png","id"=>63), array("image"=>"abc.png","id"=>65));
foreach($imageArr as $image){
/* array_column will do the job with in_array to search in the multi dimension array */
if(in_array($image['id'], array_column($subcat, 'id'))){
echo 'exists'. $image['id'].'<br>';
}else{
echo 'not exists'. $image['id'].'<br>';
}
}

PHP: Check if the value exists in csv file

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.

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);

Checking if excel cell has a value

I need to dynamically generate table headings from an excel file so that the results are output in the following fashion:
Value of country1
Value of country2
Value of country4
If they contain a value, note that there is no country 3
Someone kindly helped me with the following script
// Loop the array
foreach ($vCountries as $key => $value) {
// If value is not empty
if (!empty($value)) {
// display the line
echo '<th id="'.$key.'">'.$value.'</th>'."\n";
}
}
But now I need to access and check the excel spreadsheet to check if there is a value. So somehow I need to take the following code (that's my guess by the way)
//For example, not certain if I can use range in this context in PHP
$data->sheets[0]['cells'].range[6][9].value
And stick it into this statement
if (!empty($value)) {
As I have only been doing PHP for 5 days, my brains are scrambling...
Any help?
If you're using PHP-ExcelReader, then something like this should work
$sheet = 0;
$row = 6;
$col = 9;
if (array_key_exists($row,$data->sheets[$sheet]['cells']) && array_key_exists($col,$data->sheets[$sheet]['cells'][$row])) {
// cell exists
} else {
// cell does not exist
}
That is basically the code used internally by PHP-ExcelReader
alternatively:
if(isset($data->sheets[$sheet]['cells'][$row][$col]) {
// cell exists
} else {
// cell does not exist
}
EDIT
Hopefully there aren't any merged cells in your worksheet

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