I need to display all the elements/objects of a JSON file. I can currently only call an endpoint that takes an offset (starting index) and limit. The maximum number of elements you could get is 100 (the limit) at one call. I was wondering how could I get all of the elements of a JSON file and store them in an array without knowing how many elements there are in the JSON file.
Initially I tried to save the first 500 elements in an array. The problem with that was that the output size of that array was 5 and not 500 because the getElements endpoint returns a list of 100 elements, so what the array actually stored was 100 elements at each index. So for example json_array[0] contains the first 100 elements, json_array[2] contains the next 100 elements etc.
$offset = 0;
$limit = 100;
$json_array = array();
while($offset < 500)
{
array_push($json_array,getElements($token,"api/Elements?offset=".$offset."&limit=".$limit));
$offset+=100;
}
echo count($json_array)
I am expecting to find a way to loop through the entire json file without knowing the number of elements that the file has. My final expectation is to find a way to display the number of all of these elements. Thank you!
I work with a similar API - there is a per_page
option and a page
option.
Fortunately, the API I'm hitting is set up to return everything with no error if there are less results than the per_page
value, so what I do is simply loop while I fetched 100 records.
Something like:
$fetched=100;
$page=0;
$per_page=100;
$total_result=array();
while($fetched==100){
$res=json_decode(file_get_contents($API_URL."?offset=".($page*$per_page));
$fetched=count($res);
// add res to big result set
for($i=0;$i<$fetched;$i++){
$total_result[]=$res[$i];
}
$page++;
}