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
Related
I'm trying out Box\Spout and rewriting some code which was formerly using PHPExcel. Iterating through rows is clear but in a few cases I need to address directly one specific row. I cannot find this in the documentation.
Something like:
$row = $sheet->getRow(8);
You can't access rows directly. If you need the 8th row, you'll need to read the first 8 rows... This is because Spout does not load the entire spreadsheet in memory so it reads the data row by row.
However, you can do something like this:
foreach ($reader->getSheetIterator() as $sheet) {
foreach ($sheet->getRowIterator() as $rowIndex => $row) {
if ($rowIndex !== 8) {
continue;
}
// do something with row 8
}
}
Try using the iterator's key() method:
$it = $sheet->getRowIterator();
$row = $it->key(8);
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>';
}
}
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.
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
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;