I am using multiple mysql queries from different databases, pulling out the values from the while loop with arrays and them reuniting them in a loop as this one:
$len = max(count($insrtdate),count($energy));
for($i=0;$i<$len;$i++){
$date = isset($insrtdate[$i]) ? $insrtdate[$i] : '';
$energy1 = isset($energy[$i]) ? $energy[$i] : '';
echo $energy1;
}
The value $energy1 is initially 0 and i want to detect the row in which this changes to any number and the row in which this returns to the initial value of 0.
I'm not 100% sure that I understand your question, but this should be what you want:
$len = max(count($insrtdate), count($energy));
$lastEnergy1 = null;
for($i=0; $i < $len; $i++){
$date = isset($insrtdate[$i]) ? $insrtdate[$i] : '';
$energy1 = isset($energy[$i]) ? $energy[$i] : '';
if ($lastEnergy1 !== $energy1) {
$onState = ($energy1 == "1" ? "on" : "off");
echo "Energy1 turned " . $onState . " at " . $date . "<br />";
$lastEnergy1 = $energy1;
}
}
Related
I have this array which contain around 1000 records. I want to display 20 array records per page.
$list=array(
array([title]=>"sony", [description]=>"camera"),
array([title]=>"sony", [description]=>"mobiles"),
array([title]=>"lenovo", [description]=>"laptop"),
array([title]=>"lenovo", [description]=>"mobiles")
);
I have used the following code for pagination. It is giving me a long row for pagination. Can someone help me to include previous and next code to my existing code so that my pagination will look good.
$page = isset($_REQUEST['page']) && $_REQUEST['page'] > 0 ? $_REQUEST['page'] : 1;
function display($list, $page = 1)
{
$start = ($page - 1) * 2;
$list = array_slice($list, $start, 15);
foreach ($list as $key => $val) {
echo $val['title'] . '<br/>';
echo $val['description'] . '<br/>';
echo "<br>";
}} $len = count($list);
$pages = ceil($len / 2);
if ($page > $pages or $page < 1)
{
echo 'page not found';
}
else
{
display($list, $page);
for ($i = 1 ; $i <= $pages ; $i++)
{
$current = ($i == $page) ? TRUE : FALSE;
if ($current) {
echo '<b>' . $i . '</b>';
}
else
{
?>
<?php echo $i;?>
<?php
}
}
}
Here's an example with the data array from your question.
The example
The page size is assumed to be 2 (20 in your question).
The size of the data array does not matter.
The start parameter is provided (as in your example) thru a GET parameter http://localhost/flipkart-api/fkt_offer.php?…start=index_or_page. This parameter is available in the script as $_GET['start'].
The previous and next start indices are to be calculated ($start +/- $maxpage, etc.).
To keep this example simple, I took the start index, not the page number, as parameter. But you also could use a page number and calculate the index, of course.
For the reason of brevity I omitted error checking ("what if no more items", etc.).
Code:
<?php
// The data array
$list=array(
array('title'=>"sony", 'description'=>"camera"),
array('title'=>"sony", 'description'=>"mobiles"),
array('title'=>"lenovo", 'description'=>"laptop"),
array('title'=>"lenovo", 'description'=>"mobiles")
);
// Evaluate URL
$proto = ((isset($_SERVER["HTTPS"])) && (strtoupper($_SERVER["HTTPS"]) == 'ON')) ? "https://" : "http://";
$hname = getenv("SERVER_NAME");
$port = getenv("SERVER_PORT");
if ( (($port==80)&&($proto=='http://')) || (($port==443)&&($proto=='https://')) ) { $port = ''; }
$params = '';
foreach ($_GET as $key=>$value) {
if (strtolower($key)=='start') continue;
$params .= (empty($params)) ? "$key=$value" : "&$key=$value";
}
$url = $proto . $hname . $port. $_SERVER['SCRIPT_NAME'] . '?' . $params;
// Page contents
$last = count($list)-1;
$start = (isset($_GET['start'])) ? intval($_GET['start']) : 0;
if ($start<0) $start = 0; if ($start > $last) $start = $last;
$maxpage = 2;
echo "<p>Start index = $start</p>" . PHP_EOL;
$curpage = 0;
for($xi=$start; $xi<=$last; $xi++) {
if ($curpage >= $maxpage) break;
$curpage++;
echo 'Entry ' . $curpage .
': ' . $list[$xi]['title'] .
' - ' . $list[$xi]['description'] .
'<br />' . PHP_EOL;
}
// Navigation
$prev = $start - $maxpage; if ($prev<0) $prev = 0;
$next = ( ($start+$maxpage) > $last) ? $start : $start + $maxpage;
$prev = ( ($start-$maxpage) < 0) ? 0 : $start - $maxpage;
echo '<p>Previous ';
echo 'Next</p>';
?>
Result (e.g)
Start index = 2
Entry 1: lenovo - laptop
Entry 2: lenovo - mobiles
Previous Next
I've wrote a script in PHP for an university big data project.
The following code should support following function:
Read amount of data from a table
read a subset of the same table und extend it with 2 columns which calculate 2 values.
generate f.e. 1000 inserts and commit them to an other table
do this for the whole dataset of point 1
My problem:
0-1000:
my solution inserts in the first try 1000 datalines
1000-2000:
in this step it inserts 2000 datalines, so after the 2nd step it seems to insert 0-2000 datalines of the origin dataset. In sum 3000 datalines.
I'm a little bit out of ideas... I don't see my failure.
<?php
$user = 'root';
$pass = '';
$kill = 0;
echo 'Connecting to DB:';
try {
$db1 = new PDO('mysql:host=localhost;dbname=itt2_joined;charset=utf8',$user,$pass);
$db1->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
echo "OK \nGOING2COPY!\n";
}
catch(PDOException $ex) {
echo " Failed - Process stopped!\n";
$kill = 1;
}
if(!$kill) {
$stmt = 'SELECT
`id_transaction`
FROM
`database_joined_full`
WHERE
`relative_delivery_date` > 0
AND
`relative_received_date` > 0
AND
`relative_issued_date` > 0';
$setSize = $db1->query($stmt)->rowCount();
echo "No. Of Datasets: " . $setSize . "\n";
$stepSize = 1000;
echo "Start Copy $stepSize Datasets per Query! \n";
$copy = 1;
$lower = 0;
$upper = 0;
echo "[";
while($copy) {
$lower = $upper;
$upper += $stepSize;
$upper = ($upper > $setSize ? $setSize : $upper);
$data = $db1->query("SELECT
`id_transaction`,
`id_order_line`,
`relative_transaction_date`,
`relative_requested_date`,
`new_requested_qty`, `new_requested_price`,
`relative_suggested_date`,
`new_suggested_qty`,
`delivery_qty`,
`relative_delivery_date`,
`received_qty`,
`relative_received_date`,
`id_order_header`,
`delivery_counter`,
`relative_issued_date`,
`relative_xcurrent_date`,
`issued_quantity`,
`current_quantity`,
`product_code`,
`destination`,
`relative_issuing_date`,
`delivery_location`,
`issuer`,
`id_supplier`,
`currency`,
`shipment`,
`issued_price4unit`,
`current_price4unit`,
`total_delivered`
FROM
`database_joined_full`
WHERE
`relative_delivery_date` > 0
AND
`relative_received_date` > 0
AND
`relative_issued_date` > 0
LIMIT $lower OFFSET $stepSize")->fetchAll();
$db1->beginTransaction();
foreach($data as $row) {
$sql = "";
$sql = "INSERT INTO `refactored_data` (`id_transaction`, `id_order_line`, `relative_transaction_date`,
`relative_requested_date`, `new_requested_qty`, `new_requested_price`, `relative_suggested_date`,
`new_suggested_qty`, `delivery_qty`, `relative_delivery_date`, `received_qty`,
`relative_received_date`, `id_order_header`, `delivery_counter`, `relative_issued_date`,
`relative_xcurrent_date`, `issued_quantity`, `current_quantity`, `product_code`, `destination`,
`relative_issuing_date`, `delivery_location`, `issuer`, `id_supplier`, `currency`, `shipment`,
`issued_price4unit`, `current_price4unit`, `total_delivered`, `shipment_delay`, `sending_delayed`) VALUES ";
$sql .= "(";
for($i = 0; $i<sizeof($row)/2; $i++) {
$sql .= "'".$row[$i] . "', ";
}
$sql .= $row['relative_received_date'] - $row['relative_delivery_date'] . ',';
$sql .= ($row['relative_received_date'] <= $row['relative_issued_date'] ? 1 : 0) .')';
$db1->prepare($sql)->execute();
}
$db1->commit();
// Statusbar
//echo "\n$lower - $upper\n";
$perc = ceil(($upper/$setSize) *40);
$bar = "\r[". str_repeat("=", $perc - 1). ">";
$bar .= str_repeat(" ", 40 - $perc) . "] - " . number_format($upper / $setSize * 100, 3) ."% ";
echo "\033$bar"; // Note the \033. Put the cursor at the beginning of the line
//While_Exit
$copy = ($upper == $setSize ? 0 : 1);
//$copy = 0;
}
echo "\nall done, BYE! \n";
}
?>
You're using the stepsize as the offset each time:
LIMIT $lower OFFSET $stepSize
Should be:
LIMIT $stepSize OFFSET $lower
Oh thank you! I haven't seen the failure.
Now the code works, nearly completely, my last problem is the following:
in the first Select query i get from '->rowCount();' the number of rows of the select query.
But with my insertion copys a bit more data. But in the second Select i have the same Where clause likewise the first Select query.
I get from the CLI-Print : No. of Rows: 655056
and it writes in the Database 658597
so how do i get the 3541 rows?
or is maybe a failure inside the Insert?
Greetings
I have an interface where a user will enter the name of a company. It then compares what they typed to current entries in the database, and if something similar is found it presents them with options (in case they misspelled) or they can click a button which confirms what they typed is definitely new and unique.
The problem I am having is that it is not very accurate and often brings up dozens of "similar" matches that aren't that similar at all!
Here is what I have now, the first large function I didn't make and I am not clear on what exactly it does. Is there are much simpler way to acheive what I want?
// Compares strings and determines how similar they are based on a nth letter split comparison.
function cmp_by_optionNumber($b, $a) {
if ($a["score"] == $b["score"]) return 0;
if ($a["score"] > $b["score"]) return 1;
return -1;
}
function string_compare($str_a, $str_b)
{
$length = strlen($str_a);
$length_b = strlen($str_b);
$i = 0;
$segmentcount = 0;
$segmentsinfo = array();
$segment = '';
while ($i < $length)
{
$char = substr($str_a, $i, 1);
if (strpos($str_b, $char) !== FALSE)
{
$segment = $segment.$char;
if (strpos($str_b, $segment) !== FALSE)
{
$segmentpos_a = $i - strlen($segment) + 1;
$segmentpos_b = strpos($str_b, $segment);
$positiondiff = abs($segmentpos_a - $segmentpos_b);
$posfactor = ($length - $positiondiff) / $length_b; // <-- ?
$lengthfactor = strlen($segment)/$length;
$segmentsinfo[$segmentcount] = array( 'segment' => $segment, 'score' => ($posfactor * $lengthfactor));
}
else
{
$segment = '';
$i--;
$segmentcount++;
}
}
else
{
$segment = '';
$segmentcount++;
}
$i++;
}
// PHP 5.3 lambda in array_map
$totalscore = array_sum(array_map(function($v) { return $v['score']; }, $segmentsinfo));
return $totalscore;
}
$q = $_POST['stringA'] ;
$qLengthMin = strlen($q) - 5 ; // Part of search calibration. Smaller number = stricter.
$qLengthMax = strlen($q) + 2 ; // not in use.
$main = array() ;
include("pdoconnect.php") ;
$result = $dbh->query("SELECT id, name FROM entity_details WHERE
name LIKE '{$q[0]}%'
AND CHAR_LENGTH(name) >= '$qLengthMin'
#LIMIT 50") ; // The first letter MUST be correct. This assumption makes checker faster and reduces irrelivant results.
$x = 0 ;
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$percent = string_compare(strtolower($q), strtolower(rawurldecode($row['name']))) ;
if($percent == 1) {
//echo 1 ;// 1 signifies an exact match on a company already in our DB.
echo $row['id'] ;
exit() ;
}
elseif($percent >= 0.6) { // Part of search calibration. Higher deci number = stricter.
$x++ ;
$main[$x]['name'] = rawurldecode($row['name']) ;
$main[$x]['score'] = round($percent, 2) * 100;
//array_push($overs, urldecode($row['name']) . " ($percent)<br />") ;
}
}
usort($main, "cmp_by_optionNumber") ;
$z = 0 ;
echo '<div style="overflow-y:scroll;height:175px;width:460px;">' ;
foreach($main as $c) {
if($c['score'] > 100) $c['score'] = 100 ;
if(count($main) > 1) {
echo '<div id="anysuggested' . $z . '" class="hoverdiv" onclick="selectAuto(' . "'score$z'" . ');">' ;
}
else echo '<div id="anysuggested' . $z . '" class="hoverdiv" style="color:#009444;" onclick="selectAuto(' . "'score$z'" . ');">' ;
echo '<span id="autoscore' . $z . '">' . $c['name'] . '</span></div>' ;
$z++ ;
}
echo '</div>' ;
Comparing strings is a huge topic and there are many ways to do it. One very common algorithm is called the Levenshtein difference. This is a native implementation in PHP but none in MySQL. There is however an implementation here that you could use.
You need aproximate/fuzzy string matching.
Read more about
http://php.net/manual/en/function.levenshtein.php, http://www.slideshare.net/kyleburton/fuzzy-string-matching
The best way would be to use some index based search engine like SOLR http://lucene.apache.org/solr/.
Is there a easier/better way to get every second hour than this
if(date("H")=='00'){$chart_updates = '|02|04|06|08|10|12|14|16|18|20|22|00';}
if(date("H")=='01'){$chart_updates = '|03|05|07|09|11|13|15|17|19|19|23|01';}
if(date("H")=='02'){$chart_updates = '|04|06|08|10|12|14|16|18|20|21|00|02';}
if(date("H")=='03'){$chart_updates = '|05|07|09|11|13|15|17|19|21|23|01|03';}
if(date("H")=='04'){$chart_updates = '|06|08|10|12|14|16|18|20|22|00|02|04';}
if(date("H")=='05'){$chart_updates = '|07|09|11|13|15|17|19|21|23|01|03|05';}
if(date("H")=='06'){$chart_updates = '|08|10|12|14|16|18|20|22|00|02|04|06';}
if(date("H")=='07'){$chart_updates = '|09|11|13|15|17|19|21|23|01|03|05|07';}
if(date("H")=='08'){$chart_updates = '|10|12|14|16|18|20|22|00|02|04|06|08';}
if(date("H")=='09'){$chart_updates = '|11|13|15|17|19|21|23|01|03|05|07|09';}
if(date("H")=='10'){$chart_updates = '|12|14|16|18|20|22|00|02|04|06|08|10';}
if(date("H")=='11'){$chart_updates = '|13|15|17|19|21|23|01|03|05|07|09|11';}
if(date("H")=='12'){$chart_updates = '|14|16|18|20|22|00|02|04|06|08|10|12';}
if(date("H")=='13'){$chart_updates = '|15|07|19|21|23|01|03|05|07|09|11|13';}
if(date("H")=='14'){$chart_updates = '|16|08|20|22|00|02|04|06|08|10|12|14';}
if(date("H")=='15'){$chart_updates = '|17|09|21|23|01|03|05|07|09|11|13|15';}
if(date("H")=='16'){$chart_updates = '|18|20|22|00|02|04|06|08|10|12|16|16';}
if(date("H")=='17'){$chart_updates = '|19|21|23|01|03|05|07|09|11|13|15|17';}
if(date("H")=='18'){$chart_updates = '|20|22|00|02|04|06|08|10|12|14|16|18';}
if(date("H")=='19'){$chart_updates = '|21|23|01|03|05|07|09|11|13|15|17|19';}
if(date("H")=='20'){$chart_updates = '|22|00|02|04|06|08|10|12|14|16|18|20';}
if(date("H")=='21'){$chart_updates = '|23|01|03|05|07|09|11|13|15|17|19|21';}
if(date("H")=='22'){$chart_updates = '|00|02|04|06|08|10|12|14|16|18|20|22';}
if(date("H")=='23'){$chart_updates = '|01|03|05|07|09|11|13|15|17|19|21|23';}
I need this for google charts and wanted to check if this way is stupid.
1) take the current hour
2) mod2 (there are only two different sets of numbers, odd and even)
3) build array of hours
4) sort array by value
5) split array where the original hour was, and recombine.
$h = date("H");
$line = '';
for($i=0; $i<=24; $i++)
{
if($i % 2 == $h % 2)
$line .= '|' . ($i < 10 ? '0'.$i : $i);
}
One way is to create an array with keys:
$theHour['00'] = '|02|04|06|08|10|12|14|16|18|20|22|00';
Then you can call it like this:
$chart_updates = $theHour[date("H")];
There is also probably a better way to generate this too, but since you already typed it out, its there.. It would just suck if you want to make a change.
Nice code :)
There's actually much easier way to do this in php:
$chars = array();
$start = date("H")+2;
for( $i = 0; $i < 12; $i++){
$chars[] = str_pad( ($start+2*$i)%24, 2, '0', STR_PAD_LEFT);
}
$chart_updates = '|' . implode( '|', $chars);
function helper_add($h,$plus=0){
if($h+$plus > 23){
return $h+$plus-24;
}
return $h+$plus;
}
function helper_10($in){
return $in < 10 ? '0'.$in : $in;
}
function getchartupdates(){
$now = date('G');
for($i=($now%2==0?0:1); $i<=24 ;$i+=2)
$res[] = helper_10(helper_add($now,$i));
return '|'.implode('|',$res);
}
used this to test it !
How can I format this code block so that every time this loop happens,
it moves each hyperlink element 20px from the left?
It's working at the moment but for the whole div not single items.
Example:
- LINK 1
-- LINK 2
--- LINK 3
Any help would be appreciated!
$linkArray = array();
$thisDir = '';
$baseDir = ($htmlRoot == '') ? '' : $htmlRoot;
for ($n=0; $n<count($dirArray); $n++) {
$thisDir .= $dirArray[$n].'/';
$thisIndex = MPBCDirIndex($htmlRoot.$thisDir);
$thisText = ($n == 0) ? $topLevelName : MPBCFixNames($dirArray[$n]);
$thisLink = ($thisIndex != '') ? '<span style="padding-left:20px;">'.$thisText.'</span>' : $thisText;
if ($thisLink != '') $linkArray[] = $thisLink;
}
$results = (count($linkArray) > 0) ? implode($separator, $linkArray) : '';
Well hmmm. You are already counting your iterations with the $n variable. SO:
EG.
for ($n=0; $n<count($dirArray); $n++) {
$pxvar = $n * 20;
$thisDir .= $dirArray[$n].'/';
$thisIndex = MPBCDirIndex($htmlRoot.$thisDir);
$thisText = ($n == 0) ? $topLevelName : MPBCFixNames($dirArray[$n]);
$thisLink = ($thisIndex != '') ? '<span style="padding-left:'.$pxvar.'px;">'.$thisText.'</span>' : $thisText;
if ($thisLink != '') $linkArray[] = $thisLink;
}
Note: the first iteration will have a padding of 0px. Not sure if thats how you want it?