Remove hidden rows when reading file with phpExcel? - php

When reading a sheet with phpExcel using the toArray method, hidden rows are also parsed.
Is there a method I can use before toArray to remove hidden rows?
Code so far, using Codeigniter
$this->load->library('excel');
$objPHPExcel = PHPExcel_IOFactory::load($upload_data['full_path']);
foreach ($objPHPExcel->getAllSheets() as $sheet) {
$sheets[$sheet->getTitle()] = $sheet->toArray();
}
$data = array();
foreach ($sheets['Data'] as $key => $row) {
if ($key > 0) {
$item = array();
$item['name'] = $row[1];
$item['code'] = $row[2];
$data[] = $item;
}
}

When converting the sheet to Array using PHPExcel_Worksheet::toArray you will get all of the rows, regardless if they are visible or not.
If you want to filter only the visible rows you will have to iterate over the rows and check for each of them if they are visible or not. You can check the visibility of a row using
$sheet->getRowDimension($row_id)->getVisible()
$row_id starts with 1 (and not 0), same is in excel
Here is an example of how to use it in your code. I changed a bit the way you get the Data sheet, since you don't need to iterate over the sheets, you can just get that specific sheet using the getSheetByName function.
$data_sheet = $objPHPExcel->getSheetByName('Data');
$data_array = $data_sheet->toArray();
$data = [];
foreach ($data_sheet->getRowIterator() as $row_id => $row) {
if ($data_sheet->getRowDimension($row_id)->getVisible()) {
// I guess you don't need the Headers row, note that now it's row number 1
if ($row_id > 1) {
$item = array();
$item['name'] = $data_array[$row_id-1][1];
$item['code'] = $data_array[$row_id-1][2];
$data[] = $item;
}
}
}

Related

Updating a specific item in a shopping list csv using php

As you can see I have a majority of the step done. My goal is to create a basic shopping list using 0 for not checked off, and 1 for checked off. If a user inputs the name of the list and the item they wish check off the list the 0 will be replaced by a 1. I know I have to loop over each row in the csv and then edit the item the user inputs in the terminal. However I think I did something slightly wrong in the while loop and need help on where to fix. Here is my code:
<?php
$args = $argv;
if(!isset($args[2])) {
echo 'Not given a shopping list title or item to edit!' . PHP_EOL;
exit(1);
}
$listName = $args[1];
$fileName = $listName . '.csv';
$path = __DIR__ . '/../storage/' . $fileName;
$resource = fopen($path, 'a+');
$item = $args[2];
$rows = [];
while(($row = fgetcsv($resource)) !== false) {
$rows[] = $row;
if($rows === $item) {
$item[1] = 1;
}
while($rows == 0) {
fputcsv($resource, $rows);
}
}
fclose($resource);
Here is my csv:
bananas,0
apples,0
lettuce,0
potatoes,0
pasta,0
rice,0
tofu,0
tempeh,0
berries,0
For example if the user wishes to check off rice the 0 will be replaced with a 1.
Edit: The code works up until if($rows === $item) statement. What I am doing with while(($row=fgetcsv($resource)) !== false) { $rows[] = $row; } is get each row of the csv in one array because when I ran the code I only got the first line of the code. And then I add it to the empty rows array to make each entry (there are 9 of them to be in the same array. So when a user wishes to check an item off the list each item will be in the same array and easier to refer to.
This part
if($rows === $item) {
$item[1] = 1;
}
while($rows == 0) {
fputcsv($resource, $rows);
}
I am unsure about because I want to target the 1st index point of whatever item the user types in and wants to check off.

how to loop through array with dynamic keys in PHP

I have an array data where I am storing the result of an SQL query as below :
$stmt = sqlsrv_query($db,$sql);
$data = [];
while($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
if(!empty($row)) { $data[] = $row; } }
then I want to create a group key which is the concatenation of specific keys of my array data as below :
foreach ($data as $d) {
$group_key = $d['id'].'_'.$d['Country'].'_'.$d['Order Numer'];
//rest of my code
}
it works fine but I want to choose the keys dynamically instead of setting up manually id, Country and Order Number...
let's say I have an array $PostKeys = ["id","Country","Order Number"]; this array will vary depending on the values selected by user...
What I did is :
$PostKeys = ["id","Country","Order Number"];
foreach ($data as $d) {
foreach($PostKeys as $value)
{ $array_group_key[] = $d[$value] ; }
$group_key = implode("_",$array_group_key);
// rest of my code
}
I am supposed to get the same result but there is always mismatch. I didn't figure out where is the issue exactly. Any suggestions please ? Thank you very much.
You need to empty $array_group_key each time through the loop. Otherwise, you're appending to the results from all the previous rows.
foreach ($data as $d) {
$array_group_key = [];
foreach($PostKeys as $value)
{
$array_group_key[] = $d[$value] ;
}
}

How to pull csv import into an associative array and name the keys automatically?

I have a csv file where the first line shows the name of each row. This name should be the key for an associative array. Currently I am pulling this in manually and if the row order changes it will break the functionality.
How can I retrieve the names from line 1 and create keys out of it?
$csv = array();
$index = 0;
while ($row = fgetcsv($fp)) {
if ($row[0] == NULL)
continue;
else{
$index++;
foreach($row as $csvdata){
list(
$csv[$index]['column 1 name'],
$csv[$index]['column 2 name']
)
= explode(';',$csvdata);
}
}
}
Try converting the very first line of the file, which contains the names/keys, into an array. Then use those keys to populate the associate array as you parse the remaining lines.
$keys = array();
$csv = array();
$index = 0;
while ($row = fgetcsv($fp)) {
if ($index == 0) {
$keys = explode(',', $row);
}
else {
$csv[$keys[index-1]] = $row;
}
++$index;
}
This answer assumes that what you want here is an associate array where the keys correspond to the names in the first row, and the values correspond to each row in the CSV import.

PHP: show only last data from same data on loop

i have data from php loop foreach like this
foreach ($query->result() as $row) {
echo $row->name;
}
how to make the result show only the end data without remove others if data has same (if data have same value, hide all except the last one) like this:
*sorry bad english, this is the first time i ask here. thank you
Online Check, This is just a demo example.
See below the real example:
At first you need to use array_search for get the position of the same data, if exist then just remove it using $arr[$pos] = '';, and each and every time you need to import data into the new array called $arr and after completing fetching data you need to use a foreach loop to print them.
$arr = array();
foreach($query->result() as $row){
$pos = array_search($row->name, $arr);
if($pos !== false)
$arr[$pos] = '';
$arr[] = $row->name;
}
foreach($arr as $val){
echo $val.'<br/>';
}
Check this and let me know.
The data_seek method might help. This assumes your array is reasonable ordered to begin with.
$rowCount = 0;
$res = $query->result();
foreach($res as $row) {
if ($rowCount < $res->num_rows - 1) {
// set internal pointer to next row
$res->data_seek($rowCount + 1);
// if the row names match, print an empty string
// otherwise print the current name
$nextRow = $res->fetch_row();
if ($row->name == $nextRow->name) {
echo "";
// reset the internal pointer
$res->data_seek($rowCount);
} else {
echo $row->name;
}
} else {
echo $row->name;
}
// update the row count
$rowCount += 1;
}

How to read empty cells in PHPExcel?

This following code simply ignore all empty cells in my excelsheet.
Is there any way to read empty cell or replace them to "Null" values?
See the code here---https://arjunphp.com/how-to-use-phpexcel-with-codeigniter/
$file = './files/test.xlsx';
//load the excel library
$this->load->library('excel');
//read file from path
$objPHPExcel = PHPExcel_IOFactory::load($file);
//get only the Cell Collection
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
$maxCell = $objPHPExcel->getHighestRowAndColumn();
$newdata = array();
//extract to a PHP readable array format
foreach ($cell_collection as $cell) {
I tried this following code
$newdata = $objPHPExcel->rangeToArray($cell . $maxCell['column'] . $maxCell['row']);
$newdata = array_map('array_filter', $data);
$newdata = array_filter($data);
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
//header will/should be in row 1 only. of course this can be modified to suit your need.
if ($row == 1) {
$header[$row][$column] = $data_value;
} else {
$arr_data[$row][$column] = $data_value;
}
}
//send the data in an array format
$data['header'] = $header;
$data['values'] = $arr_data;
print_r($newdata);
Get this error messgae... Fatal error: Call to undefined method PHPExcel::getHighestRowAndColumn()
you're try to wrong way, in this way you only get the last active cell value and if you try to get empty cell cell value in middle you're not able to get value. and you use some PhpSpreadsheet function and also some time you try get value using class object. check your code one more time.

Categories