I have 31 rows in my DB and I want to load them with 2 seconds interval. But when sleep function is live for 60 seconds, main function repeats and $count resets.
My code:
$count = 0;
$files_count = count($files);
foreach($files as $file) {
$count++;
$bot_file_name = $file['bot_file_name'];
$bot_file_tg_id = $file['bot_file_tg_id'];
$bot_file_format = $file['bot_file_format'];
if ($bot_file_format == "pdf") {
// do something
} else if ($bot_file_format == "video") {
// do something
} else if ($bot_file_format == "audio") {
// do something
}
if ($count == $files_count) {
break;
}
sleep(2);
}
I can't understand what is wrong here.
php max_execution_time is 120.
Related
I had a job interview test and the question I got was about making a function which would return the number of ways a number could be generated by using numbers from a certain set and any number in the set can be used N times.
It is like if I have the number 10 and I want to find out how many ways 10 can be generated using [2,3,5]
2+2+2+2+2 = 10
5+3+2 = 10
2+2+3+3 = 10
5+5 = 10
to solve it I made this function:
function getNumberOfWays($money, $coins) {
static $level = 0;
if (!$level) {
sort($coins);
}
if ($level && !$money) {
return 1;
} elseif (!$level && !$money) {
return 0;
}
if ($money === 1 && array_search(1, $coins) !== false) {
return 1;
} elseif ($money === 1 && array_search(1, $coins) === false) {
return 0;
}
$r = 0;
$tmpCoins = $coins;
foreach ($coins as $index => $coin) {
if (!$coin || $coin > $money) {
continue;
}
$tmpCoins[$index] = 0;
$tmpMoney = $money;
do {
$tmpMoney -= $coin;
if ($tmpMoney >= 0) {
$level++;
$r += getNumberOfWays($tmpMoney, $tmpCoins);
$level--;
} elseif (!$tmpMoney) {
$r++;
}
} while ($tmpMoney >= 0);
}
return $r;
}
This function works ok and returns the right value.
My question is if there is a better way for it.
Thanks
The below code works and does output exactly what i want. I made a foreach loop getting the values of a specific field ($CustomFields...) which is part of a framework variable. Then is only counts that field when the condition is "group".
After that i want to het the average price of all fields / count.
// ########### Get average hourly rate for group classes
$itemsperhour = array();
$countperhour = 0;
foreach($listings as $listing) {
if ($CustomFields->fieldValue('jr_typeoflesson',$listing,false,false) == 'group') {
$itemsperhour[] = $CustomFields->field('jr_hourlyrateus',$listing,false,false);
$countperhour = $countperhour + 1;
}
}
//print_r($items);
if ($countperhour > 0) {
$totalperhour = array_sum($itemsperhour);
$averageperhour =($totalperhour / $countperhour);
echo round($averageperhour,2);
} else {
echo "No data";
}
unset ($averageperhour);
As said, the snippet works. But may I ask how other people would write such a script related to optimise such a piece of code (for speed and readability?
PHP 5.6+
Jasper
Below is one way of optimizing:
$totalperhour = 0;
$countperhour = 0;
foreach($listings as $listing) {
if ($CustomFields->fieldValue('jr_typeoflesson',$listing,false,false) == 'group') {
$totalperhour += $CustomFields->field('jr_hourlyrateus',$listing,false,false);
$countperhour = $countperhour + 1;
}
}
if($countperhour > 0) {
$averageperhour =($totalperhour / $countperhour);
echo round($averageperhour,2);
$averageperhour = '';
} else {
echo "No data";
}
I would suppose to use array_reduce function for getting the average:
$averageperhour = array_reduce($listings, function($average, $listing) use (&$CustomFields)
{
static $sum = 0;
static $counter = 0;
if ($CustomFields->fieldValue('jr_typeoflesson', $listing, false, false) == 'group') {
$sum += $CustomFields->field('jr_hourlyrateus', $listing, false, false);
$counter ++;
$average = round(($sum / $counter), 2);
}
return $average;
}, 'No data');
echo $averageperhour;
Not sure about speed improvement (needs testing), but this variant seems to me like more readable.
How about this?
$itemsPerHour = [];
foreach($listings as $listing) {
if ($CustomFields->fieldValue('jr_typeoflesson', $listing, false, false) !== 'group') {
continue;
}
$itemsPerHour[] = $CustomFields->field('jr_hourlyrateus', $listing, false, false);
}
$countPerHour = count($itemsPerHour);
if ($countPerHour > 0) {
$averagePerHour = array_sum($itemsPerHour) / $countPerHour;
echo round($averagePerHour,2);
} else {
echo "No data";
}
This is the problem I'm having with code:
I have a function that creates an updating bar;
I have a function that creates a loop, each number of loop makes some other stuffs and the same number represent the progress of the bar (from 1 to 155);
this loop works when user make a "search" on the site for "all" countries;
BUT user can also make a "search" only choosing 1-5 different countries;
this way we have a function that makes the PROGRESS BAR, another one that makes the PROGRESS PART of the BAR that should understand how to progress.
So the point is that I don't know how make the function for progress bar to interpret the situation in order to know that user choosed only some countries and not "all" countries (the option will post to the function some "numbers of the loop" like "3", "4", "56"... corresponding to choosed country) - and this is the easy part (with maybe isset($var)).
The next hard part is that after that it will be called the PROGRESS BAR function with those "country-numbers" so that if you choose "Canada-USA-France" the numbers will be "34-12-45" and the progress bar will write "34%-12%-45%".
But it's incorrect because if you have 3 options choosed, it should be 33%-66%-99% (and not 34%-12%-45%)...
What I don't know is how to make that function understand that everytime the function receive the "country-number", and it comes from user choice different from "all", the function should get that number and modify it (and this can be made with an array) in order to adapt it to the correct bar progression so that if you have: 34, than 12 than 45, the function should understand that the 1st time 34 should become 33, the 2nd time 12 should become 66 and the 3rd time 45 should become 99 (or 100)...
Here is the code part of interest:
1. receiving _POST and verifying it:
function getData() {
$a = strtolower($_POST["CountryOne"]);
$b = strtolower($_POST["CountryTwo"]);
$c = strtolower($_POST["CountryThree"]);
$d = strtolower($_POST["CountryFour"]);
$d = strtolower($_POST["CountryFive"]);
$numPost = count($_POST);
if ($numPost == 0) {
echo("<p class='Verify'>Select an option to start search...<br></p>");
} else {
echo "<div class='Verify' id='progressbar' style='width:620px;height:16px'></div>
<div class='VerifyBar' id='information' style='width'></div>";
};
2. Jump to next part after checking it user choosed "all" or "some countries" - here is the loop:
function loopNum($x) {
$i = 0+$x;
$y = $x+3;
for ($x = $i; $x <= $y; $x++) {
$iscountryID = ("$country".$x."");
createUrl($iscountryID);
} if($y != 155) {
return loopNum($x);
} else if($y < 155) {
echo("<font size='2' face='Tahoma, Geneva, sans-serif' style='font-variant: small-caps' color='#FF0000'><i>ERROR: unxepected data extraction interruption</font></i><br>");
} else {
echo("<font size='2' face='Tahoma, Geneva, sans-serif' style='font-variant: small-caps' color='#00CC00'><i>FINISHED: data extraction ended</font></i><br>");
}};
3. than it makes a lot of other stuff and call progress bar function
function completeBar($iscountryID) {
//***** PART UNDER CONSTRUCTION WHERE I NEED HELP *****
$countryOne = strtolower($_POST["CountryOne"]);
$countryTwo = strtolower($_POST["CountryTwo"]);
$countryThree = strtolower($_POST["CountryThree"]);
$countryFour = strtolower($_POST["CountryFour"]);
$countryFive = strtolower($_POST["CountryFive"]);
if (($countryOne !== 'all') and ($countryTwo !== 'all') and ($countryThree !== 'all') and ($countryFour !== 'all') and ($countryFive !== 'all')) {
$numQuery = array("$countryOne","$countryTwo","$countryThree","$countryFour","$countryFive");
foreach ($numQuery as $value) {
if(is_numeric($value)) {
$j++;
}}; // AT THIS POINT I WOULD KNOW HOW MANY VALUES IN THE ARREY ARE DIFFERENT FROM "ALL" AND "NO_COUNTRY" OPTIONS AND SO ARE NUMERIC VALUES
//***** FROM HERE I DUNNO HOW TO PRECEED *****
} else { //the next part works with "all" option choosed
if ($iscountryID < 155) {
$i = $iscountryID;
$percent = $i."%";
$pxbar = 4*$i."px";
$percentage = round((($pxbar*100)/624),0); //bar is 624px long
// Javascript for updating the progress bar and information
echo '<script language="javascript">
document.getElementById("progressbar").innerHTML="<div style=\"width:'.$pxbar.';background-color:#ddd;\">'.$percentage.'% </div>";
document.getElementById("information").innerHTML="'.$i.'/155 country(s) processed... loading your data, hold on..."</script>';
// This is for the buffer achieve the minimum size in order to flush data
echo str_repeat(' ',1024*64);
// Send output to browser immediately
flush();
sleep(1);
} else if ($iscountryID == 155) { //so on loop complete
$i = $iscountryID;
$percent = $i."%";
$pxbar = 4*$i."px";
$percentage = round((($pxbar*100)/624),0);
echo '<script language="javascript">
document.getElementById("progressbar").innerHTML="<div style=\"width:'.$pxbar.';background-color:#ddd;\">'.$percentage.'% </div>";
document.getElementById("information").innerHTML="'.$i.'/155 country(s) processed... loading your data, hold on..."</script>';
echo str_repeat(' ',1024*64);
flush();
sleep(1);
// Tell user that the process is completed
echo '<script language="javascript">
document.getElementById("progressbar").innerHTML="<div style=\"width:'.$pxbar.';background-color:#ddd;\">100% </div>";
document.getElementById("information").innerHTML="<div>Process completed, all countries verified...</div>";
document.getElementById("information").style.color="green";
</script>';
echo str_repeat(' ',1024*64);
flush();
sleep(1);
}
}};
Ah... I've tried to make the following working but the problem is that with the following, I'll have the function updating the bar getting values from the array too fast. Using the VAR sent from the rest of the file, I'll have an updating bar that follows the updating output of the server.
function partialBar() {
$countryOne = strtolower($_POST["CountryOne"]);
$countryTwo = strtolower($_POST["CountryTwo"]);
$countryThree = strtolower($_POST["CountryThree"]);
$countryFour = strtolower($_POST["CountryFour"]);
$countryFive = strtolower($_POST["CountryFive"]);
$numQuery = array("$countryOne","$countryTwo","$countryThree","$countryFour","$countryFive");
foreach ($numQuery as $value) {
if(is_numeric($value)) {
$j++;
};
};
if ($j == 1) {
$iscountryID = 155;
completeBar($iscountryID);
} else if ($j == 2) {
$iscountryID = array("78","155");
completeBar($iscountryID[0]);
completeBar($iscountryID[1]);
} else if ($j == 3) {
$iscountryID = array("52","104","155");
completeBar($iscountryID[0]);
completeBar($iscountryID[1]);
completeBar($iscountryID[2]);
} else if ($j == 4) {
$iscountryID = array("39","78","117","155");
completeBar($iscountryID[0]);
completeBar($iscountryID[1]);
completeBar($iscountryID[2]);
completeBar($iscountryID[3]);
} else if ($j == 5) {
$iscountryID = array("31","62","93","124","155"); //these numbers are the corresponding loop number in other to get 20%-40%-60%-80%-100% from the completeBar() function
completeBar($iscountryID[0]);
completeBar($iscountryID[1]);
completeBar($iscountryID[2]);
completeBar($iscountryID[3]);
completeBar($iscountryID[4]);
} else echo ("<div class='Verify'>Something went wrong!</div>");
};
Here is solution:
make a counter in the central function in order to know how many times have been called, so you know which number of the array you have to call for the correct calculation of the % of progress bar.
Here is where the following functions are called:
if (($countryNameTitOne == 'all') or ($countryNameTitTwo == 'all')
or ($countryNameTitThree == 'all') or ($countryNameTitFour == 'all')
or ($countryNameTitFive == 'all')) {
completeBar($iscountryID);
} else {
$callCounter = callCounterFunc();
partialbar($iscountryID,$callCounter);
}};
Than here are the functions called:
function completeBar($iscountryID) {
if ($iscountryID < 155) {
$i = $iscountryID;
$percent = $i."%";
$pxbar = 4*$i."px";
$percentage = round((($pxbar*100)/624),0);
echo '<script language="javascript">
document.getElementById("progressbar").innerHTML="<div style=\"width:'.$pxbar.';background-color:#ddd;\">'.$percentage.'% </div>";
document.getElementById("information").innerHTML="'.$i.'/155 country(s) processed... loading your data, hold on..."</script>';
echo str_repeat(' ',1024*64);
flush();
sleep(1);
} else if ($iscountryID == 155) {
$i = $iscountryID;
$percent = $i."%";
$pxbar = 4*$i."px";
$percentage = round((($pxbar*100)/624),0);
echo '<script language="javascript">
document.getElementById("progressbar").innerHTML="<div style=\"width:'.$pxbar.';background-color:#ddd;\">'.$percentage.'% </div>";
document.getElementById("information").innerHTML="'.$i.'/155 country(s) processed... loading your data, hold on..."</script>';
echo str_repeat(' ',1024*64);
flush();
sleep(1);
echo '<script language="javascript">
document.getElementById("progressbar").innerHTML="<div style=\"width:'.$pxbar.';background-color:#ddd;\">100% </div>";
document.getElementById("information").innerHTML="<div>Process completed, all countries verified...</div>";
document.getElementById("information").style.color="green";
</script>';
echo str_repeat(' ',1024*64);
flush();
sleep(1);
}
};
function partialBar($iscountryID,$callCounter) {
$countryOne = strtolower($_POST["CountryOne"]);
$countryTwo = strtolower($_POST["CountryTwo"]);
$countryThree = strtolower($_POST["CountryThree"]);
$countryFour = strtolower($_POST["CountryFour"]);
$countryFive = strtolower($_POST["CountryFive"]);
$numQuery = array("$countryOne","$countryTwo","$countryThree","$countryFour","$countryFive");
foreach ($numQuery as $value) {
if(is_numeric($value)) {
$j++;
}};
if ($j == 1) {
if ($callCounter == 1) {
$iscountryID = 155;
completeBar($iscountryID);
};
} else if ($j == 2) {
$iscountryID = array("78","155");
if ($callCounter == 1) {
completeBar($iscountryID[0]);
} else if ($callCounter == 2) {
completeBar($iscountryID[1]);
};
} else if ($j == 3) {
$iscountryID = array("52","104","155");
if ($callCounter == 1) {
completeBar($iscountryID[0]);
} else if ($callCounter == 2) {
completeBar($iscountryID[1]);
} else if ($callCounter == 3) {
completeBar($iscountryID[2]);
};
} else if ($j == 4) {
$iscountryID = array("39","78","117","155");
if ($callCounter == 1) {
completeBar($iscountryID[0]);
} else if ($callCounter == 2) {
completeBar($iscountryID[1]);
} else if ($callCounter == 3) {
completeBar($iscountryID[2]);
} else if ($callCounter == 4) {
completeBar($iscountryID[3]);
};
} else if ($j == 5) {
$iscountryID = array("31","62","93","124","155");
if ($callCounter == 1) {
completeBar($iscountryID[0]);
} else if ($callCounter == 2) {
completeBar($iscountryID[1]);
} else if ($callCounter == 3) {
completeBar($iscountryID[2]);
} else if ($callCounter == 4) {
completeBar($iscountryID[3]);
} else if ($callCounter == 5) {
completeBar($iscountryID[4]);
};
} else echo ("<div class='Verify'>Something went wrong!</div>");
};
function callCounterFunc() {
static $calls = 0;
++$calls;
return $calls;
};
my database has 25000 rows.
Using a While-loop i get the data.
Now i want to use SLEEP() everytime 500 rows are picked up.
I created the script below, but this script only works one time at 500 rows.
<?php
$i=0;
while($value = mysql_fetch_assoc($result)) {
if($i == 500) {
// sleep for 10 seconds
sleep(10);
}
//continue
$i++;
}
?>
How to mainupulate this script to make it work every 500 rows?
You need to replace ($i == 500) by ($i%500 == 0)
<?php
$i=0;
while($value = mysql_fetch_assoc($result)) {
if($i % 500 == 0) {
// sleep for 10 seconds
sleep(10);
}
//continue
$i++;
}
?>
Use this
while($value = mysql_fetch_assoc($result)) {
if($i % 500 == 0) {
// sleep for 10 seconds
sleep(10);
}
//continue
$i++;
}
?>
check $i%500
<?php
$i=0;
while($value = mysql_fetch_assoc($result)) {
if($i%500 == 0) {
// sleep for 10 seconds
sleep(10);
}
//continue
$i++;
}
?>
<?php
$i = 0;
while($value = mysql_fetch_assoc($result)) {
if(++$i % 500 === 0) {
// sleep for 10 seconds
sleep(10);
}
}
?>
I have a problem with my script im using. the if $addcount is not working. it continues to fire the insertMessage function when i dont want it to. Any ideas why?
if(($result->data != '') && ($result->data != null)) {
$wallCount = 0;
$addCount = 0;
foreach($result->data as $thread){
$wallCount++;
$fromId = $thread->from->id;
$message = $thread;
if($fromId == $user['Id']){
if($addCount < 100) {
insertMessage($user['Id'], $message, $user['Num']);
$addCount++;
sleep(1);
}
}
}
}
From your script, it will call insertMessage 100 times (0-99). Before the if statement, echo the counter to see what it is doing:
...
echo $addCount."<br />";
if($addCount < 100) {
...