Adding some data to an array - php

ok here is some code
$highestRow = 16; // e.g. 10
$highestColumn = 'F'; // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn); // e.g. 5
for ($row = 9; $row <= $highestRow; ++$row) {
$val=array(); //i have initialized the array
for ($col = 1; $col <= $highestColumnIndex; ++$col) {
$cell=$objWorksheet->getCellByColumnAndRow($col, $row);
$val[]=$cell->getValue();
}
echo $val[0] //from what is read from excel, it returns data like this 7563
}
How the data was in the excel sheet before, B9 had 75, B10 had 6 and B11 had 3
After reading i echo $val[0] //output 7563
Now i would like to add additional data to the result so if i echo $val[0] after adding the info it shows the output as
echo $val[0] //output average=75% ; rsd = 6%; n=3% instead of just 7563

foreach ($k as $key=>$value) {
echo $key."=".$value."; ";
}

Depending on the type of array that you have you can either directly edit it as a string, or you have to turn it into a string.
If the value is already a string you can simply do string manipulation, you can create a temporary or use the original string and edit it all at once to be echoed, depends on what you prefer.
$strTemp = "output average=substr($var[0],0,2)% ; "rsd =substr($var[0]%,2,1); n=substr($var[0]%,3,1);" //can also use $var[0] instead of strTemp
If the values are in integer format you will have to turn the values into strings and then you can move on from there. If you don't know how, I advise this thread: Converting an integer to a string in PHP
Another thing, I'd advise storing the numbers in different parts of the array, that way its easier to reference them and tell them apart.

Related

Delete row phpexcel

I want to load my file.xls and check if my elements contains the character ^; then, I want to remove it.
Here my code so far:
$objPHPExcel = PHPExcel_IOFactory::load("trainbayes.xlsx");
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet){
$column = 'C';
$lastRow = $worksheet->getHighestRow();
for ($row = 2; $row <= $lastRow; $row++) {
$cell = $worksheet->getCell($column.$row);
if (preg_match("/([\^])/",$cell)){
$objPHPExcel->getActiveSheet()->removeRow($row,$row);
}
}
}
But it didn't work. Can you help me? Thank you :)
$cell = $worksheet->getCell($column.$row);
Returns a Cell object and assigns it to $cell; you are then treating that cell object as though it was a string in your preg_match() call.
Surely you should be checking the value of the cell
$cell = $worksheet->getCell($column.$row)->getValue();
Additionally,
$objPHPExcel->getActiveSheet()->removeRow($row,$row);
Do you really mean to pass $row twice? Second argument is the number of rows to delete, first argument is the row number to start deleting, so if you pass $row is 5, then PHPExcel will delete 5 rows, starting at row number 5.
Surely you mean
$objPHPExcel->getActiveSheet()->removeRow($row, 1);
or simply
$objPHPExcel->getActiveSheet()->removeRow($row);

PHPExcel loop through rows and columns

Need help identifying weird problem that i'm facing. I did tried searching in stack overflow but didn't find any possible answer.
Here is sample program that works displaying all rows and columns on UI
<?php
date_default_timezone_set('America/Los_Angeles');
require_once 'PHPExcel-1.8/Classes/PHPExcel.php';
include 'PHPExcel-1.8/Classes/PHPExcel/IOFactory.php';
$path = 'demo.xlsx';
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
for ($row = 2; $row <= $highestRow; ++ $row) {
$val=array();
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getValue();
//End of For loop
}
$Col1 = $val[0] ;
$Col2 = $val[1] ;
$Col3 = $val[2];
echo $Col1;
echo $Col2;
echo $Col3;
echo "<br>";
//End of for loop
}
?>
This program works perfectly fine printing all columns and rows for n-lenght
Problem - Now our requirement is to get values of Col1, Col2, Col3 and using mysql_query compare into database and do further action.
Minute we add anything above //End of for loop. It only iterates once and stops without throwing any php errors.
e.g.
.....
echo $Col1;
echo $Col2;
echo $Col3;
echo "<br>";
**$sql = mysql_query("select COALESCE(MAX(SrNo), 0) AS Max_No from TABLEA where ColumnA = 1 and ColumnB = '$Col3'");
$row = mysql_fetch_array($sql);
echo $row["Max_No"];**
//End of for loop
}
?>
If we add above SQL the same program only iterates once and stops? It doesn't show any errors in logs or on screen.
Thanks in advance for your help!.
If you try to iterate with for ($col = 2; $col <= $highestColumn; ++ $col){...} it will work for columns from A to Z, but it fails pass the Z (Ex. iterate between 'A' to 'AB').
In order to iterate pass 'Z', you need to convert the column to integer, increment, compare, and get it as string again:
$MAX_COL = $sheet->getHighestDataColumn();
$MAX_COL_INDEX = PHPExcel_Cell::columnIndexFromString($MAX_COL);
for($index=0 ; $index <= $MAX_COL_INDEX ; $index++){
$col = PHPExcel_Cell::stringFromColumnIndex($index);
// do something, like set the column width...
$sheet->getColumnDimension($col)->setAutoSize(TRUE);
}
With this, you easy iterate pass the 'Z' column.
As you're using the same variable $row for the row number in the Excel iteration and for the result of your select query, it's not surprising that you're running into problems.....
The integer value that holds the Excel row number is being overwritten by the array that you get from your SQL query, and then you're trying to use that result array as the next Excel row number
Solution: Use a different variable for these two elements.
$rowData = mysql_fetch_array($sql);
echo $rowData["Max_No"];**

get key and value of second last element of an array

i have an array of undefined size, for example :
<?php
$array["foo"] = 86 ;
$array["bar"] = 49 ;
$array["matt"] = 96 ;
?>
i don't want to disturb array's internal pointer , but want to get a COPY of second last value of array instead.
I don't know, why you use a map, when in fact you want an ordered list instead, but
$tmp = array_values($array);
echo $tmp[count($tmp) -2];
should do it. With php5.4 this should work either
echo array_values($array)[count($array)-2];
I'm not sure what size your array is planned for, so copying all values into a separate array might not be a good idea.
The following code slices out an array of length 1 just from the second last position and sets $key and $value.
$pair = array_slice($array, -2, 1, true);
$key = key($pair);
$value = current($pair);
PS: Should probably be put into a simple separated function?!
You can do it this way.
$array["foo"] = 86 ;
$array["bar"] = 49 ;
$array["matt"] = 96 ;
$x = count($array);
foreach($array as $row)
{
if($x == 2)
{ $secondLast = $row;}
$x--;
}
echo $secondLast;
Because you are using associative array.

PHPExcel Column Loop

How can I do a loop which based on Excel worksheet columns? I found (and used) WorksheetIterator, RowIterator and CellIterator but nothing about columns.
There is no ColumnIterator, so you'll have to do this by hand.
For any given worksheet:
To loop rows for a column:
$column = 'A';
$lastRow = $worksheet->getHighestRow();
for ($row = 1; $row <= $lastRow; $row++) {
$cell = $worksheet->getCell($column.$row);
// Do what you want with the cell
}
To loop columns in a row, you can take advantage of PHP's Perls-style ability to increment characters:
$row = 1;
$lastColumn = $worksheet->getHighestColumn();
$lastColumn++;
for ($column = 'A'; $column != $lastColumn; $column++) {
$cell = $worksheet->getCell($column.$row);
// Do what you want with the cell
}
Note that when comparing column letters to test for the last column in the loop, we can't simply use < or <= because we're comparing strings, and "B" > "AZ" in standard string comparison, so we use a != comparison, having incremented the highest column value to give the first column ID past the end point.
You can also use
$worksheet->cellExists($column.$row);
in the loop to test for the existence of a cell before accessing it using getCell() (or not) to emulate the iterator getIterateOnlyExistingCells() behaviour
The iterators are actually fairly slow, so you may well find these simple loops are faster than using the iterators.
UPDATE (2015-05-06)
PHPExcel version 1.8.1 has introduced a new Column Iterator. The Row and Column iterators also allows you to specify a range of rows or columns to iterate, and allow you to use prev() and well as next() when looping through
This short snippet provides loop throught rows of columns.
It gets the indexes of last non empty column (and its row) and loops to that indexes, so be aware of forgotten values in excel.
Code loops throught rows of column A, then rows of column B ...
$objReader = new PHPExcel_Reader_Excel2007();
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($file);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet)
{
$worksheetTitle = $worksheet->getTitle();
$highestColumn = $worksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
// expects same number of row records for all columns
$highestRow = $worksheet->getHighestRow();
for($col = 0; $col < $highestColumnIndex; $col++)
{
// if you do not expect same number of row records for all columns
// get highest row index for each column
// $highestRow = $worksheet->getHighestRow();
for ($row = 1; $row <= $highestRow; $row++)
{
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
// do what you want with cell value
}
}
}
loop columns as range
foreach ( range('A', $Excel->getActiveSheet()->getHighestColumn()) as $column_key) {
}
Try this! Work!
$limit = 10000;
$value='sua mensagem'
for($i=0,$j='A';$i<$limit;$i++,$j++) {
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue($j.$i, $value);
}
set in $value what you want print.
This is the fix for the getColumnLetter method of the last message, it allows you to get the "letters" of the columns, whatever the number of columns you have
function getColumnLetter( $number ){
$prefix = '';
$suffix = '';
$prefNum = intval( $number/26 );
if( $number > 25 ){
$prefix = getColumnLetter( $prefNum - 1 );
}
$suffix = chr( fmod( $number, 26 )+65 );
return $prefix.$suffix;
}
This recursive method was designed allows you to get the "letters" of the columns, whatever the number of columns you have, from "A" to "ZZZZZZZZZ..." :
function getColumnLetter( $number )
{
$prefix = '';
$suffix = '';
$prefNum = intval( $number/26 );
if( $prefNum > 25 )
{
$prefix = getColumnLetter( $prefNum );
}
$suffix = chr( fmod( $number, 26 )+65 );
return $prefix.$suffix;
}
So you can loop the columns of an PHP array on index number and convert it to a string of letters and use it in PHPExcel methods, like "setCellValue" ...
But solutions above are surely faster if you can use them !
In PhpSpreadsheet ( which replaces PHPExcel ) you can do:
foreach( $sheet->getColumnIterator() as $col )
{
$sheet->getColumnDimension( $col->getColumnIndex() )->setAutosize( true );
}

PHP how do i write a multi dimmensional array into file

I am trying to use files to hold an array for checkers
this is the array
$board = array(
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0),
array(0,0,0,0,0,0,0,0,0)
);
while also giving the values so that i can set the beginning of the board with the pieces placed in a predefined positions to start the game in then have them user input which location they want to move the pieces into
I already have this while loop
$row = 0;
print "<form>";
print "<table border = 1>";
while ($row < 8){ // Counts to 8. (from 0...7 = 8 times. 0 ... 8 = 9 times)
print "<tr>";
$row++;
$col = 0; // reset column to 0 each time printing one row.
while ($col < 8){
print "<td>";
if($Board[$row][$col] == 0)
{
$value=$row.$col;
print "<input type=\"checkbox\" name=\"box[]\" value=\"$value\">";
// Add \ before " otherwise it will treat as the end of the quote.
}
print "</td>";
$col++;
}
print "</tr>";
}
print "</table>";
print "</form>";
}
file_put_contents($f, serialize($board));
this will serialize your multidimensional array in a file.
To read it back, use
$board = unserialize(file_get_contents($f));
2 variants:
using serialize
#dump:
file_put_contents('file_name', serialize($board));
#restore:
$board=unserialize(file_get_contents('file_name'));
using JSON:
#dump:
file_put_contents('file_name', json_encode($board));
#restore:
$board=json_decode(file_get_contents('file_name'));
JSON variant works faster, but can dump only simple structures (strings, arrays, numbers). serialize can dump objects too but works slower and generate more output
why don't you serialize the array and store it as a string into the file. to get the array back, you can read the string from the file and un-serialize it. have a read here here
Why serialize and store ? Even you can directly print array to file
ob_start();
print_r( $yourArry);
$output = ob_get_clean();
file_put_contents( 'yourfilename.txt',$output );
See example here http://www.my-php-scripts.net/index.php/Array-Scripts/php-write-multidimensional-array-into-file-advanced-php.html

Categories