I have the following code but I am not sure how to loop and offset records to get the next 20 records using the same function loop.
gameid is zero on the first call and on the second call the gameid is 21.
$result = new ArrayObject();
$count = 0;
foreach($response as &$game) {
$game = get_object_vars($game);
if ($game['gameType'] == $gametype )
{
$result->append(array($game['gameName'], $game['gameType']));
if ($count == $gameid+19) break;
$count ++ ;
}
}
Thank You
I think you should use the concept of page size and page index.
In you case seem like you want page size of 20. Sending second request with gameid mean you want page size 20 and page index 1 (instead of 0).
So consider code like this:
$count = 0;
$pageSize = 20; // this can be const or come as param
$pageIndex = 0; // this should be as params
foreach($response as &$game) {
$game = get_object_vars($game);
if ($game['gameType'] == $gametype ) {
$count++ ;
if ($count > ($pageSize * $pageIndex))
$result->append(array($game['gameName'], $game['gameType']));
// if you over the request chunk break
if ($count > ($pageSize * ($pageIndex + 1)) break;
}
}
Related
I have a script that reads values in an external XML file using PHPExcel.php, then it prints results reading the last time a number is $extraset is found into the XML file.
My problem : i should reverse the way the script calculates the result, since my values go from the newer to the older.
Example : if the 10 value appears in row 2 and then in row 6, correct result should be : 10 appears in row 2. At the moment I get '10 appears in row 10'.
Is there a way to reverse the way phpexcel read the file ? Or maybe i can just reverse the way values are processed ? Here is the script :
<?php
require_once "Classes/PHPExcel.php";
$path = "original_source.xls";
$reader = PHPExcel_IOFactory::createReaderForFile($path);
$excel_Obj = $reader->load($path);
//Get the last sheet in excel
//$worksheet=$excel_Obj->getActiveSheet();
//Get the first sheet in excel
$worksheet=$excel_Obj->getSheet('0');
$lastRow = $worksheet->getHighestRow();
$columncount = $worksheet->getHighestDataColumn();
$columncount_number = PHPExcel_Cell::columnIndexFromString($columncount);
$row_start = 6;
$row_end = 26;
$col_start = 2; //Index of column - C
$col_end = 21; //Index of column - V
$sets = array();
for ($row = 0; $row <= $lastRow; $row++) {
$set = array();
for ($col = 0; $col <= $columncount_number; $col++) {
if ($row >= $row_start && $row <= $row_end && $col >= $col_start && $col <= $col_end) {
array_push($set, $worksheet->getCell(PHPExcel_Cell::stringFromColumnIndex($col).$row)->getValue());
}
else if ($row > $row_end) {
break;
}
}
if ($row >= $row_start && $row <= $row_end) {
array_push($sets, $set);
}
else if ($row > $row_end) {
break;
}
}
//echo '<pre>'; print_r($sets); die;
$extraset = ['113', '15', '313'];
$reverse_sets = array_reverse($sets);
foreach ($extraset as $element) {
foreach ($reverse_sets as $index => $set) {
if (in_array($element, $set)) {
$actual_index = count($reverse_sets)-$index-1;
echo "Extraset element '$element' is in set $actual_index<br>";
break;
}
}
}
?>
I was trying with array_reverse, but I only keep getting 'error 500'. I'm a bit confused.
Thanks for your help
EDIT :
The modify i did with array reverse was to remove the array reverse function, changing that part in this way, and it works properly :
foreach ($extraset as $element) {
foreach ($sets as $index => $set) {
if (in_array($element, $set)) {
$actual_index = count($sets)-$index-1;
echo "Extraset element '$element' is in set $actual_index<br>";
break;
}
}
}
?>
Now the script outputs me the right value, but what I can't fix is the way $actual_index works.
This is my actual output :
Extraset element '113' is in set 0
Extraset element '15' is in set 20
Extraset element '313' is in set 20
My problem :
The way it search the values is correct, but is wrong the way it calculates the set. Set 0 should be set 20, while set 20 should be set 0.
So basically I am trying to get the sum of AveragePrice of every single page on this api. Right now it only gets first page the things i've tried have only gotten it to go on an endless loop crashing wamp. Heres my code for 1 page of working.
I am just really unsure how I can get it to loop through pages and get sum of every page.
<?php
function getRap($userId){
$url = sprintf("https://www.roblox.com/Trade/InventoryHandler.ashx?userId=" . $userId . "&filter=0&page=1&itemsPerPage=14");
$results = file_get_contents($url);
$json = json_decode($results, true);
$data = $json['data']['InventoryItems'];
$rap = 0;
foreach($data as $var) {
$rap += $var['AveragePrice'];
}
echo $rap;
}
$userId = 1;
getRap($userId);
?>
You may get better answers by looking into the API you are working with regarding how many pages to look for. You want to loop until you hit the max pages. There should be an value in the result of your request that tells you that you've asked for a page that doesn't exist (ie. no more results). If you can get a total number of results to search for then you could do a for loop with that as your limit.
//Change the function to accept the page number as a variable
function getRap($userId, $i){
$url = sprintf("https://www.roblox.com/Trade/InventoryHandler.ashx?userId=" . $userId . "&filter=0&page=" . $i . "&itemsPerPage=14");
//work out how many pages it takes to include your total items
// ceil rounds a value up to next integer.
// ceil(20 / 14) = ceil(1.42..) == 2 ; It will return 2 and you will look for two pages
$limit = ceil($totalItems / $itemsPerPage);
// Then loop through calling the function passing the page number up to your limit.
for ($i = 0; $i < $limit; $i++) {
getRap($userId, $i);
}
If you cannot get the total number of items, you could loop while a fail state hasn't occured
// look for a fail state inside your getRap()
function getRap($userId, $i) {
if ($result = error) { //you will have to figure out what it returns on a fail
$tooMany = TRUE;
}
}
for ($i = 0; $tooMany !== TRUE ; $i++) {
getRap($userId, $i);
}
Edit: Reviewing my answer, looking for the fail state inside your function is poor form (and won't work because of the scope of the variable in this case). You could pass the variable back and forth, but I'll leave that part up to you.
To get the total, make sure that your function doesn't print the result (echo $rap) but returns it for further use.
Full example
<?php
function getRap($userId, $i){
$url = sprintf("https://www.roblox.com/Trade/InventoryHandler.ashx?userId=" . $userId . "&filter=0&page=" . $i . "&itemsPerPage=25");
$results = file_get_contents($url);
$json = json_decode($results, true);
if ($json['msg'] == "Inventory retreived!") {
$data = $json['data']['InventoryItems'];
$rap = 0;
foreach($data as $var) {
$rap += $var['AveragePrice'];
}
return $rap;
} else {
return FALSE;
}
}
$total = 0;
$userId = 1;
for ($i = 0; $i < 1000 /*arbitrary limit to prevent permanent loop*/ ; $i++) {
$result = getRap($userId, $i);
if ($result == FALSE) {
$pages = $i;
break;
} else {
$total += getRap($userId, $i);
}
}
echo "Total value of $total, across $pages pages";
?>
I currently have a method inside my "car class" that display the car:
static function getCars(){
$autos = DB::query("SELECT * FROM automoviles");
$retorno = array();
foreach($autos as $a){
$automovil = automovil::fromDB($a->marca, $a->modelo, $a->version, $a->year, $a->usuario_id, $a->kilometraje, $a->info,
$a->hits, $a->cilindrada, $a->estado, $a->color, $a->categoria, $a->precio, $a->idAutomovil);
array_push($retorno, $automovil);
}
return $retorno;
}
In my index.php I call that function
foreach(car::getCars() as $a){
That allows me to display the info this way ( of course inside the foreach I have a huge code with the details I'll display.
Is there a way to implement a pagination to that thing so I can handle 8 cars per page, instead of showing all of them at the same page?
You can add a $limit and $page parameter on your function so that it will only return a maximum of $limit number of items starting from $limit * $page(or will call it the $offset). You also need to add a function to get the total number of rows you have for automoviles table.
static function getCars($page = 0, $limit = 8){
$offset = $limit * max(0, $page - 1);
//replace this with prepared statement
$autos = DB::query("SELECT * FROM automoviles LIMIT $offset, $limit");
$retorno = array();
foreach($autos as $a){
$automovil = automovil::fromDB($a->marca, $a->modelo, $a->version, $a->year, $a->usuario_id, $a->kilometraje, $a->info,
$a->hits, $a->cilindrada, $a->estado, $a->color, $a->categoria, $a->precio, $a->idAutomovil);
array_push($retorno, $automovil);
}
return $retorno;
}
static function getTotal()
{
//query to get total number of rows in automoviles table
}
In your index.php do this:
foreach(car::getCars((isset($_GET['page']) ? $_GET['page'] : 1)) as $a){
...
}
and add the pagination links.
$total = car::getTotal();
if($total > 8) {
for($i = 1; $i <= intval(ceil(1.0 * $total / $limit)); $i++) {
echo '' . $i . ';
}
}
I am trying to construct a php script that will page through an API. The api return ~25197 XML records. I am able to pass a start_offset and a end_offset to the API which will return a subset of the results.
The challenge I am having is that the for loop is not capturing the remaining records that are not within the 1000.
Example, the current for loop processes the records in blocks of 1000 (0-1000,1001-2000,2001-3000, etc.) I am not able to get the final block - 25,000 to 26,000. The for loop stop processing at 24,000 - 25,000. This leaves me with 197 unprocessed XML results.
<?php
//Set Start and Offset Parameters
$start_offset = 0;
$end_offset = 0;
$items_per_page = 1000;
$number = 0;
$counter = -2;
for ($count=0; $count<=100; $count++) {
$counter++;
//Validate that the counter is not null
if ($number != null){
echo "\n";
echo file_get_contents($static_url . "/sc_vuln_query-compliance.php?start=$start_offset&end=$end_offset&seq=$counter");
}
//Initialize the start and end offset variables
$end_offset = $number+=$items_per_page;
$start_offset = $number-$items_per_page+1;
//We want to start at record 0, reset start_offset back to 0 instead of 1
if($start_offset == 1) {
$start_offset = $number-$items_per_page;
}
// We are at the end of the total records, display the remaining
if ($number>$total_xml_records) {
$counter = $counter+1;
$padding = $end_offset + $items_per_page;
echo "\n";
echo file_get_contents($static_url. "/sc_vuln_query-compliance.php?start=$start_offset&end=$padding&seq=$counter");
break;
}
}
?>
Your code is at least buggy at this line $padding = $end_offset + $items_per_page; - here you raise the end for your last loop by another 1000 and therefor get ?start=25001&end=27000&seq=25.
Try $padding = $total_xml_records; instead, this will get you ?start=25001&end=25197&seq=25.
Anyway your code is quite complicated. Try this:
$total_xml_records = 25197; // index 0 .. 25196
$offset = 0;
$counter = 0;
while ($offset < $total_xml_records) {
echo "\n";
echo $static_url . "/sc_vuln_query-compliance.php?start=".($offset)."&end=".(min($offset+$items_per_page-1, $total_xml_records-1))."&seq=".($counter++);
$offset += $items_per_page;
}
This script is supposed to to get a multidimensional array and iterate through the values.
The array size is 10 and each element should contain an associative array:
$games[0] => array('foo' => 'bar')
$games[1] => array('foo1' => 'bar1')
etc..
The while loop should iterate 5 times in this example. The for loop should iterate 10 times for each iteration of the while loop.
So I am expecting the echo to be:
countwhile = 5 countfor = 50 totalgames = 50
but im actually getting
countwhile = 5 countfor = 150 totalgames = 150
I believe $games array is not the problem because i have have made that call below before and have used print_r to view the contents and it is as expected.
This whole code is not in a function or class just as is on my index.php page, could the problem be to do with the variable scopes?
$totalruns = 5;
$endindx = 10;
$startindx = 0;
$countwhile = 0;
$countfor = 0;
$totalfilesize = 0;
$totalgames = 0;
$sizeof = 0;
while($totalruns > 0)
{
$games = $feedHandler->getGames($startindx, $endindx);
$sizeof = sizeof($games);
for($i=0; $i<$sizeof; $i++)
{
$totalfilesize += $games[$i]['swf_file_size'];
$countfor++;
}
$startindx += 10;
$endindx += 10;
$totalruns -= 1;
$totalgames += $sizeof;
unset($games);
}
echo'<p>' . ' countwhile = ' . $countwhile . ' countfor = ' . $countfor . '</p>';
problem 1:
$sizeof = sizeof($games)-1;
explain 1:
for($i=0, $sizeof = sizeof($games);$i<=$sizeof;$i++)
the above will execute 11 times is the sizeof($games) is 10
So, either
for($i=1, $sizeof = sizeof($games);$i<=$sizeof;$i++)
or
for($i=0, $sizeof=sizeof($games)-1;$i<=$sizeof;$i++)
problem 2 :
$e = sizeof($games);
explain 2 :
$e = count($games);
...
$e += $e;
If the final size of $games is 50, you just sum it to 100
so, it some kind of logic problem
I know the answer has been accepted, but thought I'd refactor and make this a little more clean.
function retrieveGamesInfo($limit, $start = 0)
{
$feedHandler = new FeedHandler(); // ignore this, just for testing to simluate your call
if ($start > $limit)
throw new Exception("Start index must be within the limit");
$result = Array(
'TotalGames' => 0,
'TotalFileSize' => 0
);
// iterate over the results in groups of 10
$range = $start;
while ($range < $limit)
{
$range_end = $range + 10; // change me to play with the grab amount
if ($range_end > $limit)
$range_end = $limit;
// grab the next 10 entries
$games = $feedHandler->getGames($range,$range_end);
$result['TotalGames'] += count($games);
foreach ($games as $game)
$result['TotalFileSize'] += $game['swf_file_size'];
$range = $range_end;
}
return $result;
}
var_dump(retrieveGamesInfo(50));
based one everything I've read and taken in, this should be a good supplement. The above provides the following result:
array(2) {
["TotalGames"]=>
int(50)
["TotalFileSize"]=>
int(275520)
}
As i said in my comment $e is overwritten at each loop, so what you have in $e at the end is just the last count of elements in $games *2.
Added with ajreal issues this means results are what your code is expected to render :-) and I'm quite sure your last $game is not just 10 elements but 50. Quiet sure... but it's hard to read.