How can i print array as row and column in phpExcel? - php

Here is my array output in browser which i need to print as row and column associatively in PHPEXCEL.Please suggest me how to export it as row and columns.
FirstArray
(
[0] => EY>Yes
[1] => Media Type>Category B
[2] => Coverage Type>Quote
[3] => Industry Programs>Communications
[4] => Score>1
)
code -
while ($i < count($labels)) {
$j = 0;
while ($j < count($dd1)) {
// for($j=0;$j<count($dd1);$j++) {
$temp = explode(">", $dd1[$j]);
if ($temp[0] == $labels[$i]) {
$name = explode(">", $dd1[$j]);
echo '<pre>First';
print_r($name);
}
$j++;
}
complete code i am trying to print $name array as row and column -
$inn_table = "";
for($i=0;$i<count($labels);$i++) {
for($j=0;$j<count($dd1);$j++) {
$temp = explode(">",$dd1[$j]);
if($temp[0]==$labels[$i]) {
$name = explode(">",$dd1[$j]);
//here i need to print my $name array data
}
}
echo $inn_table;

At first step you can collect once all column names and create first static row, which will work as columns:
foreach($labels[0] as $ind=>$label){
$letter = range('A', 'Z')[$ind];
$tmp = explode('>',$label);
$col_names[] = $tmp[0];
echo $letter.'1'."\r\n";
//$objPHPExcel->getActiveSheet()->setCellValue($letter.'1',$tmp[0]);
echo "Column -> $tmp[0] \r\n";
}
Now you can work with other data:
foreach ($labels as $ind=>$item){
$index = $ind + 2;
foreach($item as $ind2=>$data){
$letter = range('A', 'Z')[$ind2];
echo "$letter$index \r\n";
$val = explode('>',$data);
//$objPHPExcel->getActiveSheet()->setCellValue("$letter$index",$val[1]);
echo "Value at $index -> $val[1] \r\n\r\n";
}
echo "\r\n\r\n";
}
Demo
Note: this code is OK for A..Z range column indexes, for others you need to update this code.

Related

PHPExcel: Dynamic Row and Column incrementing is not working for Array in phpexcel?

While printing column and row from an array it's showing blank not exporting any data
$inn_table = "";
if ($result['qualification']['dd1'] != "") {
$dd1 = explode(",", $result['qualification']['dd1']);
}
if ($result['qualification']['dd2'] != "") {
$dd2 = explode(",", $result['qualification']['dd2']);
}
for ($i = 0; $i < count($labels); $i++) {
if ($result['qualification']['dd1'] != "") {
echo '<pre>First';
print_r($dd1); ** //echo arrays**
for ($j = 0; $j < count($dd1); $j++) {
$temp = explode(">", $dd1[$j]);
if ($temp[0] == $labels[$i]) {
$name = explode(">", $dd1[$j]);
echo '<pre>First ';
print_r($name[1]); ** //echo names**
}
}
}
}
Here is my Array structure
and Here names which i am trying to export from Array
So i only trying to export names from that array please help
foreach($labels as $ind => $label) {
$index = $ind + 2;
$letter = range('A', 'Z')[$ind2];
$val = explode('>', $data);
$objPHPExcel->getActiveSheet()->setCellValue($letter . $index, $val[1]);
}

add the key name and value for the same array in php

I have some array like this how can i split the key and value in php ?
[A0E4NL014XVM273] => Array
(
[0] => qexixdb
)
[A0E4UK024XVM014_Clone] => Array
(
[0] => pe8w3100
[1] => pe8w3100
)
Tried Query
foreach($vm_array as $vmkey=> $vmvalue){
$varray[] = $vmvalue;
/*foreach($vmvalue as $vmvalue=> $vmvalufmarray){
$vm_array[$vmkey][] = $vmvalufmarray.',';
}*/
}
Expected Output
[A0E4UK024XVM014_Clone] => pe8w3100,pe8w3100
You need to make a function called implode().
foreach($vm_array as $vmkey=> $vmvalue){
$varray[$vmkey] = implode(",", $vmvalue);
}
print_r($varray);
Try using PHP's implode on the inner array;
foreach($vm_array as $vmkey => $vmvalue){
$vm_array[$vmkey] = implode(",", $vmvalue);
}
I tried your example and simulated my own, if my understanding is right, if you want to retain them in the array.
$test = array("[A0E4NL014XVM273]" => array("qexixdb"),"[A0E4UK024XVM014_Clone]" => array("pe8w3100","pe8w3100"));
echo "<pre>";
var_dump($test);
echo "</pre>";
$new_arr_ = array();
foreach($test as $id => $value) {
$new_val = "";
for($i = 0, $ctr_val = count($value); $i < $ctr_val; $i++) {
$old_id = "";
if($id != $old_id) {
if($i < ($ctr_val - 1)) {
$new_val .= $value[$i] . ",";
} else {
$new_val .= $value[$i];
}
$old_id = $id;
}
}
$new_arr_[] = array($id => $new_val);
}
echo "<pre>";
var_dump($new_arr_);
echo "</pre>";
Or if just one array:
$new_arr_ = array();
foreach($test as $key=> $value){
$new_arr_[key] = implode(",", $value);
}
echo "<pre>";
var_dump($new_arr_);
echo "</pre>";
Hope it helps.

How do I put this array into csv or excel?

I can't figure out a way to do this and I really bad with working with arrays so I hope someone can help me.
I have array $stuck that just contains names, like this
$stuck = array('Daniel','Alex','alfredo','dina');
I am using sort to put the names in alphabetical order, like this
sort($stuck);
Now the thing is I want to put this array into a csv or excel file so the first letter of name will be the title and all the names with this letter will be under this title.
This is an example of what I am trying to accomplish
Here try this. I added comments between the code.
$csvArray = array();
$nameArray = array('Daniel','Alex','alfredo','dina');
//Create an array that can be used for creating the CSV
foreach($nameArray as $name)
{
$firstLetter = strtoupper(substr($name, 0,1));
$csvArray[$firstLetter][] = $name;
}
//Determine the subarray which have the must rules
$maxRuleCount = 0;
foreach($csvArray as $firstLetter => $nameArray)
{
if(count($nameArray) > $maxRuleCount)
{
$maxRuleCount = count($nameArray);
}
}
//Create the first rule (letters)
$csvContent = implode(';', array_keys($csvArray));
$csvContent .= "\r\n";
//Loop through the CSV array and create rules of the names
for($i = 0 ; $i < $maxRuleCount ; $i++)
{
foreach($csvArray as $firstLetter => $nameArray)
{
$csvContent .= #$csvArray[$firstLetter][$i].';';
}
$csvContent .= "\r\n";
}
//The hole csv content is in the $csvContent variable now
//If you want to print it you need to add the text/plain header because of the \r\n new line characters
header("Content-Type:text/plain");
echo $csvContent;
Ouput is:
D;A
Daniel;Alex;
dina;alfredo;
<?php
$stuck = array('Daniel','Alex','Dina','durban','eigor','alfredo','dina');
// associate names with first letters in a new array
foreach ($stuck as $name) {
$first_letter = strtoupper( substr( $name, 0, 1 ) );
$new_name_array[ $first_letter ][] = $name;
}
// store the first letter list in an array and sort it
$first_letters = array_keys( $new_name_array );
sort( $first_letters );
// sort the name lists
foreach( array_keys( $new_name_array ) as $letter ) {
sort( $new_name_array[$letter] );
}
// output csv header row
echo "'".implode( "','", $first_letters )."'\n";
// output the CSV name rows
$i = 0;
while ( true ) {
$row = array();
$is_row = false;
foreach( $first_letters as $letter ) {
$row[] = $new_name_array[ $letter ][ $i ];
if( ! empty( $new_name_array[ $letter ][ $i ] ) ) $is_row = true;
}
if( ! $is_row ) exit;
echo "'" . implode( "','", $row ) . "'\n";
$i++;
}
?>
Outputs quoted CSV:
'A','D','E'
'Alex','Daniel','eigor'
'alfredo','Dina',''
'','dina',''
'','durban',''
<?php
$stuck = array('Daniel','Alex','alfredo','dina', 'eigor', 'durban');
sort($stuck);
$sortedNames = array();
$maxEl = 0;
foreach ($stuck as $name) {
$name = strtolower($name);
$sortedNames[$name{0}][] = $name;
$maxEl = count($sortedNames[$name{0}]) < $maxEl ? $maxEl : count($sortedNames[$name{0}]);
}
$headers = array_keys($sortedNames);
$finalArray = array($headers);
for($i = 0; $i < $maxEl; $i++) {
$tmpRow = array();
foreach ($sortedNames as $names) {
$tmpRow[] = isset($names[$i]) ? $names[$i] : '';
}
$finalArray[] = $tmpRow;
}
$file = fopen("names.csv","w");
foreach ($finalArray as $line)
{
fputcsv($file,$line);
}
fclose($file);
Here is my attempt at this question:
$names = array('Daniel','Alex','alfredo','dina', 'eigor', 'falfoul', 'fiona');
natcasesort($names);
$columns = array();
foreach ($names as $name) {
$first = strtoupper(substr($name, 0, 1));
$columns[$first][] = $name;
}
// pad the columns so they all have the same number of rows
$maxRows = 0;
foreach ($columns as &$col) {
$numRows = count($col);
if ( $numRows > $maxRows) {
$maxRows = $numRows;
}
}
// pad the columns
foreach ($columns as &$column) {
$column = array_pad($column, $maxRows, '');
}
$firstLetter = array_keys($columns);
$numCols = count($firstLetter);
// transpose the columns array
$rows = array();
foreach ($columns as $csvCol) {
foreach ($csvCol as $k=>$n) {
$rows[$k][] = $n;
}
}
// pad the rows to ensure they all have the same number of
// columns
foreach ($rows as &$row) {
$row = array_pad($row, $numCols, '');
}
// add the title row to the rows
array_unshift($rows, $firstLetter);
$handle = fopen("names.csv", 'w');
foreach ($rows as $fRow) {
fputcsv($handle, $fRow);
}

PHP Get key value

I am trying to get the key from an array to make divs become:
<div id="item">
<div id="item-1">
<div id="item-2">
<div id="item-3">
My array code is:
$a = $something['no'];
$array = array_fill(0, $a, 'value');
foreach($array as $key => $value){
if($key == '0') {
$x = 'item';
} else {
$x = 'item-'.$key;
}
$insert .= '<div id="'.$x.'">';
// content here
$insert .= '</div>';
}
$key isn't being sent, I tried echoing $key and got no return, is there something I am missing?
Print_r on the array shows:
Array ( [0] => value [1] => value [2] => value )
Fixed Code:
$a = $something['no'];
$array = array_fill(0, $a, 'value');
foreach($array as $key => $value){
if($key == '0') {
$x = 'item';
} else {
$x = 'item-'.$key;
}
$insert .= '<div id="'.$insert = $x.'">';
// content here
$insert .= '</div>';
}
You could minimize your code with a for loop:
$something['no'] = 4;
$html = '';
for ($i = 0; $i < $something['no']; $i++) {
$x = !$i ? '' : "-{$i}";
$content = "woof woof";
$html .= "<div id=\"item{$x}\">".$content."</div>\n";
}
print_r($html);
Saves on assigning a variable and running a separate process to fill an array with numbers which you could just add up to anyway

Get 2 contents per line

I was wondering I can get these to the ID and the Name from this code:
stuffyd[1] = {name: "Item 1"};
stuffyd[2] = {name: "Item 2"};
stuffyd[3] = {name: "Item 3"};
stuffyd[4] = {name: "Item 4"};
stuffyd[5] = {name: "Item 5"};
stuffyd[6] = {name: "Item 6"};
The ID is in the [IDHERE] and the name, obviously is after name:
I tried using explode and loops but that didn't work out well. Here was my code:
<?php
function getItemName($i) {
$itemNameFile = file_get_contents('test.txt');
$itemName = explode('"', $itemNameFile);
return $itemName[$i];
}
function getItemID($i) {
$itemIDFile = file_get_contents('test.txt');
$itemID1 = explode('stuffyd[', $itemIDFile);
$itemID = explode(']', $itemID1[$i]);
return $itemID[0];
}
function getNamesID() {
for($i = 1; $i < 6; $i++) {
//if ($i & 1) {
$itemName1 = getItemName($i);
//}
//if($i < 6) {
$itemID1 = getItemID($i);
//}
}
echo $itemName1 . ":" . $itemID1 . chr(10);
}
getNamesID();
?>
This is the output:
Item 3:5
What can I do?
// read the file once only
$data = file_get_contents('test.txt');
// use preg_match_all to parse the data
preg_match_all("/stuffyd\[([0-9]+)\].*\"(.*?)\"/im", $data, $matches);
// you could echo here but let's convert the matches into a usable array
$count=count($matches);
for ($i=0; $i<$count; $i++){
$items[$matches[1][$i]]=$matches[2][$i];
}
// and then echo out the key and value of each pair
foreach ($items as $id => $name){
echo $name . ':' . $id . chr(10);
}
http://uk1.php.net/preg_match_all
The answers by #Popnoodles and #Barmar are best using preg_match_all.
But to understand why your code didn't work, there are 3 issues.
(1) in function getItemName($i) when you explode $itemNameFile the array in $itemName look like -
Array
(
[0] => stuffyd[1] = {name:
[1] => Item 1
[2] => };
stuffyd[2] = {name:
[3] => Item 2
[4] => };
stuffyd[3] = {name:
[5] => Item 3
[6] => };
stuffyd[4] = {name:
[7] => Item 4
[8] => };
stuffyd[5] = {name:
[9] => Item 5
[10] => };
stuffyd[6] = {name:
[11] => Item 6
[12] => };
)
So you need to do
return $itemName[$i+($i-1)];
(2) in function getNamesID() you are only looping through 5 time
for($i = 1; $i < 6; $i++)
to get all 6 you need to use <=6
for($i = 1; $i <= 6; $i++)
(3) in function getNamesID() your echo ... is outside of your for() loop, so you will only get the last instance. Move the for() loop closing bracket to after your echo -
echo $itemName1 . ":" . $itemID1 . chr(10);
} // end for()
} // end function
So now your code would look like -
<?php
function getItemName($i) {
$itemNameFile = file_get_contents('test.txt');
$itemName = explode('"', $itemNameFile);
return $itemName[$i+($i-1)];
}
function getItemID($i) {
$itemIDFile = file_get_contents('test.txt');
$itemID1 = explode('stuffyd[', $itemIDFile);
$itemID = explode(']', $itemID1[$i]);
return $itemID[0];
}
function getNamesID() {
for($i = 1; $i <= 6; $i++) {
$itemName1 = getItemName($i);
$itemID1 = getItemID($i);
echo $itemName1 . ":" . $itemID1 . chr(10);
}
}
getNamesID();
?>
$contents = file_get_contents("test.txt");
preg_match_all('/stuffyd\[(\d+)\].*=name:\s*"(.*)"/', $contents, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
echo $match[2] . ':' . $match[1] . "\n";
}

Categories