I'm trying to write a short script that will query my mysql db, and according to the amount of results (dynamic) i want the script on each segment.
For example, $arr is a result of a mysql_fetch_array and it has 872 items, I want to run my function 9 times, 1 for each 100 items and the last one for 72 items.
How can I do that?
Simply use a for loop with an incrementor that increments by 100. You can use array_slice() to get the concerned rows on each loop.
$dbRows = resultsFromDB();
for($i = 0; $i < count($dbRows); $i+=100) {
$concernedRows = array_slice($dbRows, $i, 100);
mySuperFunction($concernedRows);
}
Maybe something like:
$length = count($arr);
for ($i = 0; $i < ceil($length / 100); $i++) {
}
If I understood.
Related
I am writing one logic to iterate numbers first and then additional logic to putting them into particular subset of array.
What does this code do :
Code accept first $n
its create array of $n number from 1 to $n
Then started converting to subset of $main_array to possible one like
['1'] [1,2] [1,2,3] [2] [2,3] [3] etc. same like this
After creating subset i am counting those some subset which satisfy condition
Condition is xyz[0] should not come in subset with abc[0] vice versa xyz[i] should not come in subset abc[i]. Example 2 and 3 is coming subset then dont count that subset, same 1 and 4 is coming then dont count
here is my nested for loop :
$n = 1299;
$main_array = range(1,$n);
$counter = 0;
$count = sizeof($abc); // $abc and $xyz size will same always.
$abc = [2,1];
$xyz = [3,4];
for ($i=0; $i <$n; $i++) {
for($j = $i;$j < $n; $j++){
$interval_array = array();
for ($k = $i; $k <= $j; $k++){
array_push($interval_array,$main_array[$k]);
}
$counter++;
for ($l=0; $l < $count ; $l++) {
//if block here to additional condition using in_array() php function. which do $counter--
if(in_array($abc[$l], $interval_array) &&
in_array($xyz[$l], $interval_array)){
$counter--;
break;
}
}
}
}
$main_array i have to create on the spot after receiving $n values.
Following is cases :
when running $n = 4 its run in 4s
when running $n = 1200 or 1299 or more than 1000 its run in 60s-123s
Expected execution timing is 9s. I reduce from 124s to 65s by removing function calling inside for loop but its not coming to point.
Expectation of code is if i have array like
$array = [1,2,3];
then
subset need to generate :
[1],[1,2],[1,2,3],[2],[2,3],[3]
Any help in this ?
It's difficult to test performance against your experience, but this solution removes one of the loops.
The way you repeatedly build $interval_array is not needed, what this code does is to just add the new value from the main array on each $j loop. This array is then reset only in the outer loop and so it just keeps the last values and adds 1 extra value each time...
for ($i=0; $i <$n; $i++) {
$interval_array = array();
for($j = $i;$j < $n; $j++){
array_push($interval_array,$main_array[$j]);
// Check output
echo implode(",", $interval_array)."\n";
$counter++;
for ($l=0; $l < $count ; $l++) {
if(in_array($abc[$l], $interval_array) &&
in_array($xyz[$l], $interval_array)){
$counter--;
break 2;
}
}
}
}
adding "\n" to better understanding for subset flow.
import datetime
N = list(range(1, int(input("N:")) + 1))
affected_list = list(map(int, input("affected_list").split()))
poisoned_list = list(map(int, input("poisoned_list").split()))
start_time = datetime.datetime.now()
exclude_list = list(map(list, list(zip(affected_list, poisoned_list))))
final_list = []
for i in range(0, len(N)):
for j in range(i + 1, len(N) + 1):
if N[i:j] not in exclude_list:
final_list.append(N[i:j])
print(final_list)
end_time = datetime.datetime.now()
print("Total Time: ", (end_time - start_time).seconds)
Im trying to slice an array on 30 at a time to send a call to an endpoint which can only recibe 30 codes at a time. Right now I have about 203 lines in the array. Everything is fine until the 4th round where I don't know why the indexes (init and endt) I've set up, get messed up and the slice no longer works which in turns makes the call to the endpoint impossible. Here is the code:
$arrcount = ceil(count($requestarr['SelectionDetails'])/30);
$init = 0;
if (count($requestarr['SelectionDetails']) > 30) {
$endt = 29;
} else {
$endt = count($requestarr['SelectionDetails']);
}
for ($i=0; $i < $arrcount; $i++) {
$request['SelectionDetails'] = array_slice($requestarr['SelectionDetails'], $init, $endt);
$init = $endt+1;
if (count($requestarr['SelectionDetails']) > ($endt+30)) {
$endt += 30;
} else {
$endt = count($requestarr['SelectionDetails']);
}
//call to endpoind and other code here....
}
The requestarr[] has the whole 203 indexes and the request[] contains the 30 indexes slice sent each loop. Its worth noticing that my array has "custom" keys that are tracking numbers from FedEx. At the 4th loop, the init turns into 120 and the endt turns into 113. Im not sure how or why this happens. Needless to say the next 3 for loops the endt gets reduced by 7 then by 34 and finally by 1. There is no code where the endt should be decreasing. So I'm not sure how this is happening. Any ideas? If you need more information or more code I'll gladly help.
To split items into chunks - use array_chunk:
$chunks = array_chunk($your_data, 30);
foreach ($chunks as $chunk) {
// send $chunk to endpoint
}
$arrcount = ceil(count($requestarr['SelectionDetails'])/30);
for ($i=0; $i < $arrcount; $i++) {
$request['SelectionDetails'] = array_slice($requestarr['SelectionDetails'], $i * 30, 30);
//call to endpoind and other code here....
}
array_slice can take a length argument longer than the array. You just have to move the starting point.
I am not sure but when i print_r the array, both random generated string are the same instead of different.
$amount_of_files = 2;
$generated_file_names = array();
for($i = 0; $i < $amount_of_files; $i++){
$generated_file_names[] = substr(md5(time()), 0, 10);
}
time() returns it's value to the nearest second - your code is executing in much less time than that so the value is the same. If you want random values for each item in the array use rand() or mt_rand() instead.
You can use like this
<?php
$amount_of_files = 2;
$generated_file_names = array();
for($i = 0; $i < $amount_of_files; $i++){
$generated_file_names[] = substr(md5(rand()),0,10);
}
print_r($generated_file_names);
?>
you need microtime() php is looping soo fast 0 to 2 and time() is not changing so md5 is same and sub_str is same for all.
I have an array filled with data over the period of a month. The data is computed for every 15 minutes over that period, meaning it's got about 2880 entries.
I need to reduce it by about 10% in order to display the data in a chart (288 data points will render much more nicely than 2880).
Here's what I've tried (it works, but it might be a very bad method):
$count = count($this->Data1Month);
for($i = 0; $i < $count; $i += 10) {
$tempArray[] = $this->DataMonth[$i];
}
$this->Data1Month = $tempArray;
I think you have the most efficient solution, but you do have a mistake though. Array indexes start at zero so 0+10 needs to be 9, like so:
$count = count($this->Data1Month);
for($i = 0; $i < $count; $i += 9) {
$tempArray[] = $this->DataMonth[$i];
}
$this->Data1Month = $tempArray;
I am having a bit of a problem with the following code, instead of looping through 20 times it just loops through once:
$length = min($length, 20);
for ($i=0; $i<=$length; $i++)
{
$item_title=$x->item($i)->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;
echo ($item_title);
}
I need the loop to look through an RSS feed and display 20 items, but not spit out non-object errors if there is less than 20 items.
Thank you.
Your problem is that $length is 0 initially, and the min() of 0 and 20 is 0, so the loop only continues while $i <= 0.