Division by zero in pDraw php class - php

I'm trying to create a PHP script, which could draw a LineChart from MYSQL table.
Everything related with MYSQL works fine, but when I want to draw a LineChart using pChart, I'm getting error (Warning: Division by zero in ...\class\pDraw.class.php on line 3113). Please help me!
Here's the code:
<?php
include("class/pData.class.php");
include("class/pDraw.class.php");
include("class/pImage.class.php");
$filename = 'file.txt';
echo 'Status info:<br />';
$myData = new pData();
$db=mysql_connect("localhost","root","") or die("Failed to connect with database!");
echo '<br>* Connected to database successfully - OK<br />';
mysql_select_db("database", $db);
mysql_query("CREATE TABLE `measures` (
timestamp INT(10),
temperature INT(10),
humidity INT(10),
PRIMARY KEY (timestamp));");
echo "<br> * Table created successfully or it has been created earlier - OK<br />";
mysql_query("LOAD DATA INFILE '$filename' IGNORE INTO TABLE measures
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n' ")
or die("MySQL - Query Error - " . MySQL_Error());
echo "<br>* Data imported successfully - OK<br />";
$Requete = "SELECT * FROM `measures`";
$Result = mysql_query($Requete,$db);
while($row = mysql_fetch_array($Result))
{
$timestamp[] = $row["timestamp"];
$temperature[] = $row["temperature"];
$humidity[] = $row["humidity"];
}
$myData->addPoints($timestamp,"Timestamp");
$myData->addPoints($temperature,"Temperature");
$myData->addPoints($humidity,"Humidity");
$myData->setAbscissa("Timestamp");
$myData->setSerieOnAxis("Humidity", 1);
$myData->setXAxisName("Time");
$myData->setXAxisDisplay(AXIS_FORMAT_TIME,"H:i");
$myData->setAxisName(0,"Temperature");
$myData->setAxisUnit(0,"°C");
$myData->setAxisName(1,"Humidity");
$myData->setAxisUnit(0,"%");
$myPicture = new pImage(700,230,$myData);
$myPicture->drawLineChart();
?>
EDIT:
Here's the function containing line 3113 in pDraw.php
function scaleComputeY($Values,$Option="",$ReturnOnly0Height=FALSE)
{
$AxisID = isset($Option["AxisID"]) ? $Option["AxisID"] : 0;
$SerieName = isset($Option["SerieName"]) ? $Option["SerieName"] : NULL;
$Data = $this->DataSet->getData();
if ( !isset($Data["Axis"][$AxisID]) ) { return(-1); }
if ( $SerieName != NULL ) { $AxisID = $Data["Series"][$SerieName]["Axis"]; }
if ( !is_array($Values) ) { $tmp = $Values; $Values = ""; $Values[0] = $tmp; }
$Result = "";
if ( $Data["Orientation"] == SCALE_POS_LEFTRIGHT )
{
$Height = ($this->GraphAreaY2 - $this->GraphAreaY1) - $Data["Axis"][$AxisID]["Margin"]*2;
$ScaleHeight = $Data["Axis"][$AxisID]["ScaleMax"] - $Data["Axis"][$AxisID]["ScaleMin"];
$Step = $Height / $ScaleHeight;
if ( $ReturnOnly0Height )
{ foreach($Values as $Key => $Value) { if ( $Value == VOID ) { $Result[] = VOID; } else { $Result[] = $Step * $Value; } } }
else
{ foreach($Values as $Key => $Value) { if ( $Value == VOID ) { $Result[] = VOID; } else { $Result[] = $this->GraphAreaY2 - $Data["Axis"][$AxisID]["Margin"] - ($Step * ($Value-$Data["Axis"][$AxisID]["ScaleMin"])); } } }
}
else
{
$Width = ($this->GraphAreaX2 - $this->GraphAreaX1) - $Data["Axis"][$AxisID]["Margin"]*2;
$ScaleWidth = $Data["Axis"][$AxisID]["ScaleMax"] - $Data["Axis"][$AxisID]["ScaleMin"];
$Step = $Width / $ScaleWidth;
if ( $ReturnOnly0Height )
{ foreach($Values as $Key => $Value) { if ( $Value == VOID ) { $Result[] = VOID; } else { $Result[] = $Step * $Value; } } }
else
{ foreach($Values as $Key => $Value) { if ( $Value == VOID ) { $Result[] = VOID; } else { $Result[] = $this->GraphAreaX1 + $Data["Axis"][$AxisID]["Margin"] + ($Step * ($Value-$Data["Axis"][$AxisID]["ScaleMin"])); } } }
}
if ( count($Result) == 1 )
return($Result[0]);
else
return($Result);
}

You can fix it by changing this line:
$Step = $Width / $ScaleWidth;
to:
if ($ScaleWidth > 0) {
$Step = $Width / $ScaleWidth;
} else {
$Step = 1; // or change this to 0 if it doesn't work, I am not sure what this line does.
}

Related

Assign the same rank to student with the same scores

I'm assigning ranks to students based on their scores but I encountered a problem where if two or more students have the same scores they are given different ranks.
E.G John, Rita, and Mary scored 76. John is 1st, Rita is 2nd, and Mary is 3rd.
John ==> 76
Rita ==> 76
Mary ==> 76
Bukky ==>74
I want three of them to have the rank as 1st.
John ==> 76
Rita ==> 76
Mary ==> 76
Bukky ==>74
public function getStudentpositionOnlyClass($student_id, $class_id, $terms)
{
$array_product = array();
if ($class_id == 22 || $class_id == 23) {
if ($terms == 'f') {
$totField = 'ft_tot_score';
$table = 'ftscores_rn';
} elseif ($terms == 'm') {
$totField = 'mt_tot_score';
$table = 'mtscores_rn';
} elseif ($terms == 's') {
$totField = 'tot_score';
$table = 'scores_rn';
} elseif ($terms == 'h') {
$totField = 'h_tot_score';
$table = 'hscores_rn';
}
} else {
if ($terms == 'f') {
$totField = 'ft_tot_score';
$table = 'ftscores_primary';
} elseif ($terms == 'm') {
$totField = 'mt_tot_score';
$table = 'mtscores_primary';
} elseif ($terms == 's') {
$totField = 'tot_score';
$table = 'scores_primary';
} elseif ($terms == 'h') {
$totField = 'h_tot_score';
$table = 'hscores_primary';
}
}
$fail = 0;
$pass = 0;
$resultlist = $this->student_model->fullSearchByClass($class_id);
foreach ($resultlist->result_array() as $key => $stdName) {
$idd = $key + 1;
$mId[$idd] = $stdName['pstudent_id'];
$totalSubMarks = $this->db->query(
"SELECT mts.subject_id
FROM " . $table . " mts
LEFT JOIN subjects sub ON(sub.id=mts.subject_id)
WHERE class_id=" . $class_id .
" AND mts.subject_id IS NOT NULL
GROUP BY mts.subject_id ORDER BY sub.name");
$gtotal = 0;
$totSubjects = 0;
foreach ($totalSubMarks->result_array() as $tmrow) {
$totalMarks = $this->student_model->getTotalMarksForStudnets($tmrow['subject_id'],
$stdName['pstudent_id'], $table, $totField);
// //// set mtotalmark
$gtotal = $gtotal + $totalMarks;
// //// set mgtotal
$mGTotal[$idd] = $gtotal;
if ($totalMarks != 0) {
$totSubjects = $totSubjects + 1;
}
// //// set mAvg
if ($totSubjects != 0) {
$mAvg[$idd] = round($gtotal / $totSubjects, 1);
} else {
$mAvg[$idd] = 0;
}
}
// /////////
if ($totSubjects != 0) {
$percentage = ($gtotal / $totSubjects);
}
if ($percentage >= 0 && $percentage <= 39.99) {
$fail = $fail + 1;
} else {
$pass = $pass + 1;
}
}
foreach ($mAvg as $dd => $val) {
// if pure numbers store in nums array
if (! is_nan($val)) {
$nums[$dd] = $val;
}
}
arsort($nums);
$id = 1;
foreach ($nums as $kk => $av) {
foreach ($totalSubMarks->result_array() as $tmrow) {
$totalMarks = $this->student_model->getTotalMarksForStudnets($tmrow['subject_id'], $mId[$kk], $table,
$totField);
}
if ($student_id == $mId[$kk]) {
return $id;
}
// $array_product['student'.$mId[$kk]]= $id;
$id += 1;
}
}
As mickmackusa stated in his comment you have to memorize the previous score and only increment the rank if the score has changed. As you already order your results we can assume a score change between 2 iterations is always a decrease.
Your variable names are very unintuitive. So maybe my code changes are in the wrong place but you shoud understand the concept. I assume that $totSubjects is that score.
Try not to shorten a variable's name too much because you have no benifit but loose that important information on what it is. At least comment a variable assignment if its unclear what the variable holds of.
Change your loop like this:
$previousScore = null; // added THIS
foreach ($totalSubMarks->result_array() as $tmrow) {
$totalMarks = $this->student_model->getTotalMarksForStudnets($tmrow['subject_id'],
$stdName['pstudent_id'], $table, $totField);
// set mtotalmark
$gtotal = $gtotal + $totalMarks;
// set mgtotal
$mGTotal[$idd] = $gtotal;
if ($totalMarks != 0) {
if($previousScore != $totalMarks) { // added THIS
$totSubjects = $totSubjects + 1;
} else { // added THIS
$totSubjects = $totSubjects; // keep rank without incrementing
}
}
$previousScore = $totalMarks; // added THIS
// set mAvg
if ($totSubjects != 0) {
$mAvg[$idd] = round($gtotal / $totSubjects, 1);
} else {
$mAvg[$idd] = 0;
}
}
In case $gtotal or any of the other mystic variables ;) is holding the score then try to modify my given code changes to $gtotal. Shouldn't be too hard. In that case just add a comment so I can change my answer that it's actualy correct.
Hope that helps!

PHPexcel to array. Help formatting array and to rid array of NULL values

My spreadsheet will always have column B,C,D,E,F,G row 3 = address, name, phone, department, etc.. The data from the cells beneath (some empty some populated) 1234 x street, 1234 y street, 555-5555, HR, etc. So if My array could look like this:
[1] =>array(
['address1'] =>'1234 x street'
['name1'] =>'1234 y street'
['phone1'] =>'555-5555'
...etc
['department1'] =>'HR'
[2] =>array(
['address2'] =>'1234 x street'
['name2'] =>'1234 y street'
['phone2'] =>'555-5555'
...etc
['department2'] =>'HR'
My current code is:
<SNIP>
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($inputFileName);
$objWorksheet = $objPHPExcel->getActiveSheet();
if($header){
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$headingsArray = $objWorksheet->rangeToArray('A1:'.$highestColumn.'1',null, true, true, true);
$headingsArray = $headingsArray[1];
$r = -1;
$namedDataArray = array();
for ($row = 2; $row <= $highestRow; ++$row) {
$dataRow = $objWorksheet->rangeToArray('A'.$row.':'.$highestColumn.$row,null, true, true, true);
if ((isset($dataRow[$row]['A'])) && ($dataRow[$row]['A'] > '')) {
++$r;
foreach($headingsArray as $columnKey => $columnHeading) {
$namedDataArray[$r][$columnHeading] = $dataRow[$row][$columnKey];
}
}
}
}
else{
$namedDataArray = $objWorksheet->toArray(null,true,true,true);
}
Research suggests I can use one of the following methods however I need help putting it all together:
$column = 'IV';
$columnIndex = PHPExcel_Cell::columnIndexFromString($column);
$adjustment = -2;
$currentColumn = 'BZ';
$columnIndex = PHPExcel_Cell::columnIndexFromString($currentColumn);
$adjustedColumnIndex = $columnIndex + $adjustment;
$adjustedColumn = PHPExcel_Cell::stringFromColumnIndex($adjustedColumnIndex - 1);
I ended up not using any of the native classes for the sorting piece, lowered overhead by just writing it myself as follows:
<?php
//require 'FirePHPCore/fb.php'; This section was just to use FirePHP so I could see the JSON output without using html.
//ob_start('ob_gzhandler');
//FB::info('Hello, FirePHP');
//FB::log('Log message');
//FB::info('Info message');
//FB::warn('Warn message');
//FB::error('Error message');
require_once dirname(__FILE__) . '/classes/PHPExcel.php';
// Include PHPExcel_IOFactory
include 'classes/PHPExcel/IOFactory.php';
$inputFileName = './uploads/fw.xls';
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);/** Identify the type of $inputFileName **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);/** Create a new Reader of the type that has been identified **/
$objReader->setReadDataOnly(true); /** Set read type to read cell data only **/
$objPHPExcel = $objReader->load($inputFileName);/** Load $inputFileName to a PHPExcel Object **/
$objWorksheet = $objPHPExcel->getActiveSheet();//Get worksheet and built array with first row as header
// stuff all tabs into their own array
$sheetNames = $objPHPExcel->getSheetNames();
foreach ($sheetNames as $sheet) {
$sheet2 = preg_replace("/\s+/","_",$sheet);
//print "$sheet: $sheet2<br>\n";
${$sheet2} = $objPHPExcel->getSheetByName($sheet);
}
// print_r($Network_Security);
//exit;
// parse each tab, tack onto end of $prejson array
$prejson = [];
// parse network security
//use class to find data range
$highestRow = $Network_Security->getHighestRow();
$range = $Network_Security->calculateWorksheetDimension();
// manually narrow range columns
$range = preg_replace("/A/","B",$range);
$range = preg_replace("/L/","K",$range);
//create array of data rows
$rows = $Network_Security->rangeToArray($range);
$active = 0;
//loop through each row
foreach ($rows as $row) {
if (preg_match("/Do not edit the data/",$row[0])) { $active = 2; continue; }
if (preg_match("/^Line/",$row[0]) && $active == 0) { $active = 1; } //show header
if ($row[0] == "") { $active = 0; continue; }
if ($active == "1") {
//key array
array_unshift($row,"netsec");
// stuff to prejson
array_push($prejson,$row);
}
}
// end netsec
// parse network translation
$highestRow = $Network_Translation->getHighestRow();
$range = $Network_Translation->calculateWorksheetDimension();
$range = preg_replace("/A/","B",$range);
$range = preg_replace("/J/","G",$range);
$rows = $Network_Translation->rangeToArray($range);
$active = 0;
foreach ($rows as $row) {
if (preg_match("/^Source/",$row[0]) && $active == 0) { $active = 1; } //show header
if (preg_match("/Do not edit the data/",$row[0])) { $active = 2; continue; }
if ($row[0] == "") { $active = 0; continue; }
if ($active == "1") {
//key array
array_unshift($row,"nettrans");
// stuff to prejson
array_push($prejson,$row);
}
}
// end nettrans
// parse routing
$highestRow = $Routing->getHighestRow();
$range = $Routing->calculateWorksheetDimension();
$range = preg_replace("/A/","B",$range);
$range = preg_replace("/H/","G",$range);
$rows = $Routing->rangeToArray($range);
$active = 0;
foreach ($rows as $row) {
if (preg_match("/Do not edit the data/",$row[0])) { $active = 2; continue; }
//if (preg_match("/^Add/",$row[0]) && $active == 0) { $active = 1; continue; } //hide header
if (preg_match("/^Add/",$row[0]) && $active == 0) { $active = 1; } //show header
if ($row[0] == "") { $active = 0; continue; }
if ($active == "1") {
// key array
array_unshift($row,"rtg");
// stuff to prejson
array_push($prejson,$row);
}
}
// end routing
//print "<pre>";
//var_dump($prejson);
$json = json_encode($prejson);
//$json_string = prettyPrint($json);
$json_string = json_encode($json,JSON_PRETTY_PRINT); //remove ,JSON_PRETTY_PRINT
print $json;
//print "</pre>";
function prettyPrint( $json )
{
$result = '';
$level = 0;
$in_quotes = false;
$in_escape = false;
$ends_line_level = NULL;
$json_length = strlen( $json );
for( $i = 0; $i < $json_length; $i++ ) {
$char = $json[$i];
$new_line_level = NULL;
$post = "";
if( $ends_line_level !== NULL ) {
$new_line_level = $ends_line_level;
$ends_line_level = NULL;
}
if ( $in_escape ) {
$in_escape = false;
} else if( $char === '"' ) {
$in_quotes = !$in_quotes;
} else if( ! $in_quotes ) {
switch( $char ) {
case '}': case ']':
$level--;
$ends_line_level = NULL;
$new_line_level = $level;
break;
case '{': case '[':
$level++;
case ',':
$ends_line_level = $level;
break;
case ':':
$post = " ";
break;
case " ": case "\t": case "\n": case "\r":
$char = "";
$ends_line_level = $new_line_level;
$new_line_level = NULL;
break;
}
} else if ( $char === '\\' ) {
$in_escape = true;
}
if( $new_line_level !== NULL ) {
$result .= "\n".str_repeat( "\t", $new_line_level );
}
$result .= $char.$post;
}
return $result;
}
?>
Now I just need to get the hook so that when dropzone.js completes it will autopopulate the .js form.

SQLSTATE[42000]: Syntax error or access violation: 1064?

What is the problem to the code? I cannot upload to database. It comes the message:
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'ACQUA'))' at line 2
query was:
SELECT `vals`.*, `opt`.*
FROM `eav_attribute_option_value` AS `vals`
INNER JOIN `eav_attribute_option` AS `opt` ON opt.option_id = vals.option_id
WHERE (opt.attribute_id='191')
AND (vals.value in ('ALESSANDRO DELL'ACQUA'))
PHP Code:
<?php
/**
* Adapted by Christopher Shennan
* http://www.chrisshennan.com
*
* Date: 20/04/2011
*
* Adaptered from original post by Srinigenie
* Original Post - http://www.magentocommerce.com/boards/viewthread/9391/
*/
class Mage_Eav_Model_Import extends Mage_Eav_Model_Mysql4_Entity_Attribute {
private $fileName;
private $delimiter = '|';
private $enclosure = '"';
private function &getCsv() {
$file = fopen($this->fileName, "r");
while (!feof($file)) {
$csvArr[] = fgetcsv($file, 0, $this->delimiter, $this->enclosure);
}
fclose($file);
return $csvArr;
}
protected function populateOptionTable($attribId) {
echo "Upload Begin<br/>";
$fields = array();
$values = array(); // store id => values
$optionValues = array(); // option id => $values
$option = array('value' => $optionValues);
$updateOptionValId;
$values = null;
$row = null;
$disCounter = 0;
$optionTable = $this->getTable('attribute_option');
$optionValueTable = $this->getTable('attribute_option_value');
$write = $this->_getWriteAdapter();
$csvStoreArr = array();
// Get CSV into Array
$csv = & $this->getCsv();
$read = $this->_getReadAdapter();
// exit if the csv file is empty or if it contains only the headers
if (count($csv) < 1 or count($csv) == 1)
return;
$fields = $csv[0]; // get the field headers from first row of CSV
// get the store Ids
$stores = Mage::getModel('core/store')
->getResourceCollection()
->setLoadDefault(true)
->load();
// determine the stores for which option values are being uploaded for
foreach ($fields as $hdr) {
if ($hdr === 'position' || $hdr === 'isDefault' || $hdr === 'ERROR') {
continue;
}
foreach ($stores as $store) {
if ($store->getCode() === $hdr)
$csvStoreArr[$hdr] = $store->getId();
}
}
// start reading the option values - from row 1 (note that 0 represents headers)
for ($indx = 1; $indx < count($csv); $indx++) {
$values = null; // initialize to null
$row = $csv[$indx]; // get row
if (isset($row) && count($row) > 0) {
//escape the single quote
//$whereParam = $read->quote($row);
if (is_array($row))
$whereParam = '(\'' . implode($row, '\',\'') . '\')';
else if (strlen($row))
$whereParam = '(\'' . $row . '\')';
$select = $read->select()->from(array('vals' => $optionValueTable))
->join(array('opt' => $optionTable), 'opt.option_id=vals.option_id')
->where('opt.attribute_id=?', $attribId);
$select = $select
->where('vals.value in ' . $whereParam);
$optionValData = $read->fetchAll($select);
unset($select);
// get the option Id for this option
if (count($optionValData) > 0) {
$optionValDataRow = $optionValData[0];
$optionId = $optionValDataRow['option_id'];
} else
$optionId = null;
$intOptionId = (int) $optionId;
if (!$intOptionId) {
$data = array(
'attribute_id' => $attribId,
'sort_order' => isset($option['order'][$optionId]) ? $option['order'][$optionId] : 0,
);
try {
$write->insert($optionTable, $data);
$intOptionId = $write->lastInsertId();
} catch (Exception $e) {
Mage::log($e->getMessage());
}
} else {
$data = array(
'sort_order' => isset($option['order'][$optionId]) ? $option['order'][$optionId] : 0,
);
$write->update($optionTable, $data, $write->quoteInto('option_id=?', $intOptionId));
}
$colIndx = 0; //initialize row's column index
if (isset($row) && is_array($row) && count($row) > 0) {
foreach ($row as $optVal) {
if ($fields[$colIndx] !== 'position' || $fields[$colIndx] !== 'isDefault' || $fields[$colIndx] !== 'ERROR') {
$values[$csvStoreArr[$fields[$colIndx]]] = $optVal; // store id => option value
}
$colIndx++;
}
}
}
if (isset($values) && is_array($values) && count($values) > 0) {
foreach ($values as $storeId => $value) {
if (!empty($value) || strlen($value) > 0) {
$value = trim($value);
$data = array(
'option_id' => $intOptionId,
'store_id' => $storeId,
'value' => $value,
);
$optionValInsert = true;
$optionValUpdate = false;
foreach ($optionValData as $valData) {
if ((int) $valData['option_id'] === $intOptionId &&
(int) $valData['store_id'] === $storeId) {
$optionValInsert = false;
if (strcasecmp(trim($valData['value']), $value) !== 0) {
$optionValUpdate = true;
$updateOptionValId = $valData['value_id'];
}
break;
}
}
if ($optionValInsert) {
$write->insert($optionValueTable, $data);
Mage::log('Inserted Value -' . $value);
} else if ($optionValUpdate) {
$write->update($optionValueTable, $data, $write->quoteInto('option_id=?', $updateOptionValId));
Mage::log('Updated Value -' . $value);
}
}
}
}
$optionValues[$optionId] = $values;
if ($indx % 20 == 0) {
echo "" . $indx . ' - uploaded!!<br />';
Mage::log($indx . ' - attributes uploaded!!', null, $this->fileName . '.log');
}
}
echo "" . $indx . ' - uploaded!!<br />';
echo '<b> Attribute Upload Finished </b><br />';
$option['value'] = $optionValues;
return null;
}
/**
* Enter description here...
*
* #param Mage_Core_Model_Abstract $object
* #return Mage_Eav_Model_Mysql4_Entity_Attribute
*/
public function saveOptionValues($attributeId, $fn) {
$option = array();
$this->fileName = $fn;
echo '<strong>Importing Attributes</strong><br/><br/>Reading file contents - ' . $this->fileName . '<br />';
Mage::log("Upload Begin", null, $this->fileName . '.log');
// Step 1 -- Get attribute Id from attribute code
$atrribId = $attributeId; //569
// Step 2 Obtain the option values into an array
$option = $this->populateOptionTable($atrribId);
}
}
Error is because of single Quotes in the string : 'ALESSANDRO DELL'ACQUA.
SELECT vals., opt. FROM eav_attribute_option_value AS vals INNER JOIN
eav_attribute_option AS opt ON opt.option_id=vals.option_id WHERE
(opt.attribute_id='191') AND (vals.value in ('ALESSANDRO
DELL'ACQUA'))
Try using double quotes.
String Literals in MySQL [ https://dev.mysql.com/doc/refman/5.0/en/string-literals.html ]
' single quote is reserved character in MySQL and there are several ways to include quote characters within a string:
A "'" inside a string quoted with "'" may be written as ""''".
A """ inside a string quoted with """ may be written as """".
Precede the quote character by an escape character (""\").
A "'" inside a string quoted with """ needs no special treatment and
need not be doubled or escaped. In the same way, """ inside a string
quoted with "'" needs no special treatment.
To avoid this use PreparedStatement in PHP http://www.w3schools.com/php/php_mysql_prepared_statements.asp
In your query is should be like 'ALESSANDRO DELL''ACQUA' instead of 'ALESSANDRO DELL'ACQUA'

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

Why isn't my sorting algorithm working?

I'm developing a system for a client that creates a csv of packing labels which is sent to a printer. The client has six different items. Customers order products in bulk from my client. Two items (product A and product B) share the same packing line. In order to make packing more efficient my client wants to alternate between packing product A and packing product B first.
For example, if John, Sally, and James all ordered both products, the system needs to write John's orders to the csv starting with product A, Sally's orders starting with product B, and James' orders starting with product A again.
I've pasted my non-working code below, but this is really screwing with my head and I'm having a really tough time with it.
foreach($orders as $order) {
$name = null;
$phone = null;
$account = DAO_ContactPerson::get($order->account_id);
$delivery = false;
if($account->is_agency) {
$name = $order->getAttribute('name');
$phone = $order->getAttribute('phone');
} else {
$name = sprintf("%s %s",
$account->getPrimaryAddress()->first_name,
$account->getPrimaryAddress()->last_name
);
$phone = $account->phone;
}
$name = trim($name);
$phone = trim($phone);
$items = $order->getItems();
if($order->getAttribute('delivery')) {
$type = 'deliveries';
$destination = 'Delivery';
$address = sprintf("%s %s %s",
$order->getAttribute('delivery_address.line1'),
$order->getAttribute('delivery_address.line2'),
$order->getAttribute('delivery_address.postal')
);
} else {
$type = 'pickups';
$agency = DAO_ContactPerson::getAgency($order->getAttribute('pickup'));
$destination = $agency->name;
// Override account id so orders are grouped by agency
$order->account_id = $agency->id;
$address = null;
}
// var_dump($order->id);
// Init account array
if(!isset($rows[$type][$order->account_id]))
$rows[$type][$order->account_id] = array('combined' => array(), 'separate' => array());
foreach($items as $item) {
$packing = 'separated';
if($item->product_id == 3 || $item->product_id == 4)
$packing = 'combined';
if(!isset($rows[$type][$order->account_id][$packing][$item->product_id]))
$rows[$type][$order->account_id][$packing][$item->product_id] = array();
$i = 0;
while($i < $item->quantity) {
$rows[$type][$order->account_id][$packing][$item->product_id][] = array(
'number' => $order->id,
'destination' => $destination,
'size' => $item->product_id,
'name' => $name,
'address' => $address,
'phone' => $phone
);
$i++;
}
}
// if($order->id == 176) {
// var_dump($rows[$type][$order->account_id][$packing]);
// }
}
$this->weight = 1;
$pickups = count($rows['pickups']);
for($i = 0; $i < $pickups; $i++) {
$account =& $rows['pickups'][$i];
$account['output'] = array();
if(isset($account['combined'])) {
$combined_products =& $account['combined'];
if(!empty($combined_products)) {
foreach($combined_products as $prod_id => $combined) {
usort($combined_products[$prod_id], array($this, "_compareBoxes"));
}
// Flip weights once we finish with this account
$last_box = end($combined_products);
$last_box = array_pop($last_box);
reset($combined_products);
if($this->weight == 1) {
$this->weight = -1;
if($last_box['size'] == 3) {
asort($combined_products);
}
} else {
if($last_box['size'] == 4) {
arsort($combined_products);
}
$this->weight = 1;
}
foreach($combined_products as $combined) {
$account['output'][] = $combined;
}
foreach($account['separated'] as $separate) {
$account['output'][] = $separate;
}
}
} else {
if(isset($account['separated']))
$account['output'] = $account['separated'];
}
}
$deliveries = count($rows['deliveries']);
for($i = 0; $i < $deliveries; $i++) {
$account =& $rows['deliveries'][$i];
$account['output'] = array();
if(isset($account['combined'])) {
$combined_products =& $account['combined'];
if(!empty($combined_products)) {
foreach($combined_products as $prod_id => $combined) {
usort($combined_products[$prod_id], array($this, "_compareBoxes"));
}
// Flip weights once we finish with this account
$last_box = end($combined_products);
$last_box = array_pop($last_box);
reset($combined_products);
if($this->weight == 1) {
$this->weight = -1;
if($last_box['size'] == 3) {
asort($combined_products);
}
} else {
if($last_box['size'] == 4) {
arsort($combined_products);
}
$this->weight = 1;
}
foreach($combined_products as $combined) {
$account['output'][] = $combined;
}
foreach($account['separated'] as $separate) {
$account['output'][] = $separate;
}
}
} else {
if(isset($account['separated']))
$account['output'] = $account['separated'];
}
}
$rows['output'] = $rows['pickups'];
array_push($rows['output'], $rows['deliveries']);
$output = '';
foreach($rows['output'] as $account_id => $boxes) {
if(!empty($boxes['output'])) {
foreach($boxes['output'] as $labels) {
if(!empty($labels)) {
foreach($labels as $label) {
$output .= implode(',', $label) . "<br>";
}
}
}
}
}
The _compareBoxes method looks like this:
private function _compareBoxes($a, $b) {
if($a['size'] == $b['size']) {
return 0;
}
if($this->weight == 1) {
// Medium first, then Large
return ($a['size'] < $b['size']) ? -1 : 1;
}
if($this->weight == -1) {
// Large first, then Medium
return ($a['size'] > $b['size']) ? -1 : 1;
}
}

Categories