need help with php loop logic - php

This code works perfectly except that it doesn't print the last 2 rows of my csv file:
This is the file:
603629,0,ATLV0008,"Vendor1",1942.60,11/04/2010,1942.60,9/1-9/30/10,EFT-JP
603627,2,ATLV0008,"Vendor1",1242.40,11/04/2010,1242.40,7/1-7/31/10,EFT-JP
600023,0,FLD4V0003,"Vendor2",1950.00,06/15/2010,1950.00,6/14/10 Request,EFT-JP
600024,0,FLD4V0003,"Vendor2",1800.00,06/15/2010,1800.00,6/14/10 Request,EFT-JP
603631,0,ATLV5066,"Vendor2",1000.00,11/09/2010,1000.00,11/4/10 Check Request,PM2
603647,0,ATLV5027,"DVendor3",2799.80,11/15/2010,2799.80,10/1-10/31/10 Bishop,PM2
603642,5,ATLV5027,"Vendor3",482.40,11/15/2010,482.40,10/1-10/18/10 Allen,PM2
603653,0,ATLV0403,"Vendor4",931.21,11/17/2010,931.21,9/1-9/30/10,EFT-JP
603661,0,ATLV0105,"Vendor5",26.75,11/19/2010,26.75,093139,PM2
603660,1,ATLV0105,"Vendor5",5.35,11/19/2010,5.35,093472,PM2
Here is the code: (It needs to display the sum of 2 rows with the same vendor before the actual rows)
if (($handle = fopen('upload/ATLANTA.csv', "r")) !== FALSE) {
while (($row_array = fgetcsv($handle, 1000, ","))) {
foreach ($row_array as $key => $val) {
$row_array[$key] = trim(str_replace('"', '', $val));
ob_flush();
}
$complete[] = $row_array;
ob_flush();
}
}
flush();
$prevVendor = '';
$sum = 0;
$venData = '';
if (isset($complete)) {
foreach ($complete as $key => $val) {
$venData .= "<br/>";
$currVendor = $complete[$key][3];
if ($currVendor != $prevVendor){
if ($prevVendor != NULL){
print "<br/>";
print $sum . "<br/>";
print $venData;
$sum = 0; $venData = '';
}
}
foreach ($val as $ikey => $ival){
if ($ikey != 1){
$venData .= $ival . '&nbsp';
$prevVendor = $val[3];
}
}
if ($currVendor == $prevVendor){
$sum += $complete[$key][6];
}
}
}

I don't really understand your problem but if you want to get (and save it wherever you want) the sum of each vendors, you should do something like this :
$prevVendor = null;
$venData = '';
$sums = array();
if (isset($complete) && is_array($complete)) {
$lim = count($complete);
for ($key=0;$key<$lim;++$key) { // no need foreach for simple array
$venData .= "<br/>";
$currVendor = $complete[$key][3];
if ($currVendor != $prevVendor){
if ($prevVendor != null){
print "<br/>";
print $venData;
}
$venData = '';
$prevVendor = $currVendor;
$sums[$currVendor] = 0; // set the counter to 0
}
foreach ($complete[$key] as $ikey => $ival){
if ($ikey != 1){
$venData .= $ival . ' '; // is useful for you I guess
}
}
$sums[$currVendor] += $complete[$key][6]; // add amounts
}
}
if ($prevVendor != null){ // you need to do this to display the last record
print "<br/>";
print $venData;
}
var_export($sums); // check results
This can be some syntax errors ...

Related

How to export data in excel dynamically using PHPSpreadsheet/PHPExcel in PHP?

I have some data which I am trying to export in an excel sheet with help of PHP, data is dynamic so I am facing difficulties while exporting them. I have tried both in PHPExcel (which is deprecated) and in PHPSpreadsheet too. I have tried lots of solutions given in the community but no help!
How to print data dynamically in excel using PHP?
Data needs to print from column number = 36 (AK) and Row = 2
Data that needs to export:
MongoDB\Model\BSONDocument Object
(
[storage:ArrayObject:private] => Array
(
[dd1] => PWC>Yes,Deloitte>Yes,Media Type>Category A,Coverage Type>Quote,Service Line>TAX,Score>5
[dd2] => Service Line>Personal tax
)
)
though [dd1] contains labels and values too, like PWC[this is lable] >Yes [this is value], that's why I explode label and value separately.
Also, I have printed the labels in the first row already that's why I explode the value of the below code and also made a check if ($temp[0] == $labels[$i]) then only print value.
Completed Code:
$cols = 36;
for ($i = 0; $i < count($labels); $i++) {
if ($result["qualification"]["dd1"] != "") {
$found = false;
for ($j = 0; $j < count($dd1); $j++) {
$temp = explode(">", $dd1[$j]);
//need to check the weather labels of the header and these labels are the same? then only print
if ($temp[0] == $labels[$i]) {
$name = explode(">", $dd1[$j]);
$sheet->setCellValueByColumnAndRow($cols+1, $j+1, $name[1]);
$found = true;
break;
}
}
if (!$found)
$sheet->setCellValueByColumnAndRow($cols+1, $j+1 , "");
} else
$sheet->setCellValueByColumnAndRow($cols+1 , $j+1 , "");
if ($result["qualification"]["dd2"] != "") {
$found = false;
for ($j = 0; $j < count($dd2); $j++) {
$temp = explode(">", $dd2[$j]);
if ($temp[0] == $labels[$i]) {
$name = explode(">", $dd2[$j]);
$sheet->setCellValueByColumnAndRow( $cols, $j + 2, $name[1] );
$found = true;
break;
}
}
if (!$found)
$sheet->setCellValueByColumnAndRow($cols, $j+1 , "");
} else {
$sheet->setCellValueByColumnAndRow($cols , $j+1 , "");
}
$cols = $cols + 2;
}
I have tried lots of methods but no help but I made something in the HTML table which is working fine, unfortunately, I do not need an HTML table to excel because it has a lot of format issues and cons.
for reference only-
Here is the same working snippet in HTML Table:
$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']!="") {
$found=false;
for($j=0;$j<count($dd1);$j++) {
$temp = explode(">",$dd1[$j]);
if($temp[0]==$labels[$i]) {
$name = explode(">",$dd1[$j]);
$inn_table .= '<td>'.$name[1].'</td>';
$found=true;
break;
}
}
if(!$found)
$inn_table .= "<td> </td>";
}
else
$inn_table .= "<td> </td>";
if($result['qualification']['dd2']!="") {
$found=false;
// echo '<pre>ass';print_r($dd2);
for($j=0;$j<count($dd2);$j++) {
$temp = explode(">",$dd2[$j]);
if($temp[0]==$labels[$i]) {
$name = explode(">",$dd2[$j]);
$inn_table .= '<td>'.$name[1].'</td>';
$found=true;
break;
}
}
if(!$found)
$inn_table .= '<td> </td>';
}
else{
//if(count($dd2Array)>0){
$inn_table .= '<td> </td>';
//}
}
} //end of for($i=0;$i<count($labels);$i++)
echo $inn_table;
echo "</tr>";

How can i turn these into groups of 4 instep of 2?

So this is my code it takes a list o people from the database and lists them with their partners in groups. Within these groups, the user id of the people cannot appear in the same row twice. Everything works, Im just wondering how to make it echo 4 people per group versus only 2.
if ($result = $mysqli->query("SELECT * FROM performers")) {
printf("Found %d rows.\n", $result->num_rows);
$rows = array();
while ($row = $result->fetch_array()) {
foreach ($row as $key => $col) {
unset($row[$key]);
$row[strtolower($key)] = $col;
}
$rows[] = $row;
}
$current = null;
$count = 1;
while ( ! empty($rows)) {
if ($current) {
$current_performers = array($current['performerid_1'], $current['performerid_2']);
$found = false;
foreach ($rows as $key => $row) {
if ( ! in_array($row['performerid_1'], $current_performers) && ! in_array($row['performerid_2'], $current_performers)) {
$found = $key;
break;
}
}
if ($found !== false) {
echo '<li>', $rows[$found]['performance_id'], ': ', $rows[$found]['perf_name_1'], ' - ', $rows[$found]['perf_name_2'], '</li>';
unset($rows[$key]);
}
else {
echo '';
}
echo '</ul><hr />';
$current = null;
} else {
$current = array_shift($rows);
echo '<h3>Group ', $count+, '</h3>';
echo '<ul>';
echo '<li>', $current['performance_id'], ': ', $current['perf_name_1'], ' - ', $current['perf_name_2'], '</li>';
}
}
I think this should do it, but I haven't tested it (except to verify syntax) because I don't have any sample data.
$group_size = 4;
$current_performers = array();
$current_size = 0;
$count = 1;
while (!empty($rows)) {
if ($current_size == $group_size) { // End previous group
echo '</ul><hr>';
$current_performers = array();
$current_size = 0;
}
if ($current_size == 0) {
echo '<h3>Group ', $count++, '</h3>';
echo '<ul>';
}
$found = false;
foreach ($rows as $key => $row) {
if ( ! in_array($row['performerid_1'], $current_performers) && ! in_array($row['performerid_2'], $current_performers)) {
$found = true;
array_push($current_performers, $row['performerid_1'], $row['performerid_2']);
$current_size++;
echo '<li>', $row['performance_id'], ': ', $row['perf_name_1'], ' - ', $row['perf_name_2'], '</li>';
unset($rows[$key]);
break;
}
}
if (!$found) {
// Force a new group to start
$current_size = $group_size;
}
// If we have an unfinished group, finish it
if ($current_size) {
echo '</ul><hr>';
}
}

How to shuffle an array and then slice it

I have a problem with shuffling and slicing array.
I have this code:
$maxDisplayItem = $this->_getFlexformConfig('max_item_to_display', 'product_setting');
$selectedProducts = array_slice($selectedProducts, 0, $maxDisplayItem);
foreach ($selectedProducts as $_id) {
shuffle($products);
foreach ($products as $_product) {
....
}
}
My code limiting the number of displayed item but didn't shuffle it at all.
When I change the order of actions:
shuffle($selectedProducts);
foreach ($selectedProducts as $_id) {
$maxDisplayItem = $this->_getFlexformConfig('max_item_to_display', 'product_setting');
$products = array_slice($products, 0, $maxDisplayItem);
foreach ($products as $_product) {
....
}
}
the code shuffling and slicing results but only first (e.g. 3 results) from whole array who has 50 items.
Could anyone help me with this?
here is the whole function:
function displayProductList()
{
// Store View
$store = $this->getStoreViewCode();
$selectedProducts = $this->getSelectedProducts();
$products = $this->_products->getProductsFromDb($selectedProducts, $store, $this->getProductsStoragePid());
// Load Template File
$templateHtml = $this->cObj->fileResource( $this->_getConfig('templateProductList') );
$productListHtml = $this->cObj->getSubpart($templateHtml, '###PRODUCT_LIST###');
$productHtml = $this->cObj->getSubpart($productListHtml, '###PRODUCT_ITEM###');
$subPartContent = ''; $item = 0; $items = count($products); $even = true; $line = '';
shuffle($selectedProducts);
foreach ($selectedProducts as $_id) {
$maxDisplayItem = $this->_getFlexformConfig('max_item_to_display', 'product_setting');
$products = array_slice($products, 0, $maxDisplayItem);
foreach ($products as $_product) {
if ($_id === $_product['product_id']) {
$markers = $this->_products->getProductMarkers($_product);
// Even/Odd CSS Class Determination
if ($even === true) {
$line = 'even';
$even = false;
} else {
$line = 'odd';
$even = true;
}
// Class Determination First/Last
if ($item == 0) {
$markers['###EVENODD###'] = $line . ' ' . 'first';
} else if ($item == $items-1) {
$markers['###EVENODD###'] = $line . ' ' . 'last';
} else {
$markers['###EVENODD###'] = $line;
}
// Check if the product has an image
$imageHtml = '<p>'.$this->pi_getLL('template_label_no_image_available').'</p>';
if ($markers['###DETAIL_IMAGE###'] != 'no_selection') {
$imageHtml = $this->cObj->getSubpart($productHtml, '###PRODUCT_IMAGE###');
}
$p = $this->cObj->substituteSubpart($productHtml, '###PRODUCT_IMAGE###', $imageHtml);
$subPartContent .= $this->cObj->substituteMarkerArray($p, $markers);
$item++;
}
}
}
return $this->cObj->substituteSubpart($productListHtml, '###PRODUCT_ITEM###', $subPartContent);
}
function displayProductList(){
// Store View
$store = $this->getStoreViewCode();
$selectedProducts = $this->getSelectedProducts();
$products = $this->_products->getProductsFromDb($selectedProducts, $store, $this->getProductsStoragePid());
// Load Template File
$templateHtml = $this->cObj->fileResource( $this->_getConfig('templateProductList') );
$productListHtml = $this->cObj->getSubpart($templateHtml, '###PRODUCT_LIST###');
$productHtml = $this->cObj->getSubpart($productListHtml, '###PRODUCT_ITEM###');
$subPartContent = ''; $item = 0; $items = count($products); $even = true; $line = '';
$maxDisplayItem = $this->_getFlexformConfig('max_item_to_display', 'product_setting');
$products = array_slice($products, 0, $maxDisplayItem);
shuffle($products);
foreach ($products as $_product) {
$markers = $this->_products->getProductMarkers($_product);
// Even/Odd CSS Class Determination
if ($even === true) {
$line = 'even';
$even = false;
} else {
$line = 'odd';
$even = true;
}
// Class Determination First/Last
if ($item == 0) {
$markers['###EVENODD###'] = $line . ' ' . 'first';
} else if ($item == $items-1) {
$markers['###EVENODD###'] = $line . ' ' . 'last';
} else {
$markers['###EVENODD###'] = $line;
}
// Check if the product has an image
$imageHtml = '<p>'.$this->pi_getLL('template_label_no_image_available').'</p>';
if ($markers['###DETAIL_IMAGE###'] != 'no_selection') {
$imageHtml = $this->cObj->getSubpart($productHtml, '###PRODUCT_IMAGE###');
}
$p = $this->cObj->substituteSubpart($productHtml, '###PRODUCT_IMAGE###', $imageHtml);
$subPartContent .= $this->cObj->substituteMarkerArray($p, $markers);
$item++;
}
return $this->cObj->substituteSubpart($productListHtml, '###PRODUCT_ITEM###', $subPartContent);
}

getting the even index of a string

hey guys im trying to get the even indexes of a string from the db then save them in a variable then echo. but my codes seems doesnt work. please help. here it is
require_once('DBconnect.php');
$school_id = '1';
$section_id = '39';
$select_pk = "SELECT * FROM section
WHERE school_id = '$school_id'
AND section_id = '$section_id'";
$query = mysql_query($select_pk) or die (mysql_error());
while ($row = mysql_fetch_assoc($query)) {
$public_key = $row['public_key'];
}
if ($public_key) {
$leng_public_key = strlen($public_key);
$priv_key_extract = "";
$array_pki = array();
for ($i=0; $i <=$leng_public_key-1 ; $i++) {
array_push($array_pki,$public_key[$i]);
}
foreach ($array_pki as $key => $value) {
if($key % 2 == 0) {
$priv_key_extract += $public_key[$key];
} else {
$priv_key_extract ="haiiizzz";
}
}
}
echo $priv_key_extract;
as you can see im trying to use modulo 2 to see if the index is even.
I have updated your code as below, it will work now :
<?php
$public_key = 'A0L8V1I5N9';
if ($public_key) {
$leng_public_key = strlen($public_key);
$priv_key_extract = "";
$array_pki = array();
for ($i=0; $i <=$leng_public_key-1 ; $i++) {
array_push($array_pki,$public_key[$i]);
}
foreach ($array_pki as $key => $value) {
//Changed condition below $key % 2 ==0 => replaced with $key % 2 == 1
if($key % 2 == 1) {
// Changed concatenation operator , += replaced with .=
$priv_key_extract .= $public_key[$key];
} /*else {
//Commented this as it is getting overwritten
$priv_key_extract ="haiiizzz";
}*/
}
}
echo $priv_key_extract;
?>
Try this function
function extractKey($key) {
if (empty($key) || !is_string($key)) return '';
$pkey = '';
for ($i=0;$i<strlen($key);$i++) {
if ($i % 2 == 0) {
$pkey .= $key[$i];
}
}
return $pkey;
}
echo extractKey('12345678'); # => 1357

PHP - Detect change on string

I have an array which i do a foreach($array as $key => $value)
in my $key i get
name[1][1]
name[1][2]
name[1][3]
name[2][1]
name[2][2]
how can I add detect when the first index changes from [1][3]->[2][1]
any help is appreciated.
What i want to achieve is this:
<h4>Header</h4>
name[1][1]
name[1][2]
name[1][3]
<h4>Header</h4>
name[2][1]
name[2][2]
<h4>Header</h4>
name[3][1]
name[3][2]
name[3][3]
name[3][4]
Don't know if it is the best option, but this is how i managed to do it.
<?php $k = 1; $flag1 = 0; $flag2 = 1;foreach ($this->cart->product_options($items['rowid']) as $option_name => $option_value): ?>
<?php
$endpos = strpos($option_name,']');
$asd = substr($option_name,5,$endpos-5);
$this->firephp->log($asd);
if($asd % 2)
{
if($flag1 === 0)
{
echo ' <h4>Header '. $k .'</h4>';
$flag1 = 1;
$flag2 = 0;
$k++;
}
}
else
{
if($flag2 === 0)
{
echo ' <h4>Header '. $k. '</h4>';
$flag2 = 1;
$flag1 = 0;
$k++;
}
}
?>
You can try like
foreach($name as $parent_key => $parent_value){
echo "<h4>Header</h4><br/>";
foreach($name[$parent_key] as $key=>$value)
{
echo $name[$i][$key]."<br/>";
}
}
foreach($array as $key => $value){
$valuevalues = array();
foreach($value as $val){
if($val != "" && !isset($valuevalues[$key][$val]))
$valuevalues[$key][$val] = "different-than-previous";
if(!isset($valuevalues[$key][$val]))
$valuevalues[$key][$val] = "equal-to-first-value";
}
}

Categories