I am using laravel to loop through retrieving data from an api in my controller, it all works fine but for some reason in the loop if i var_dump the data i get all that should be there but outside my loop when i pass the data to my view it doesn't work.
I am running an api request and then when i get my response i am running a secondary api request for each of the original responses. here is part of code i am having issues with.
foreach(array_slice($nearbysearchresults->results, 0, 5) as $result) // slicing array to limit requests
{
$getplacedetails ="https://maps.googleapis.com/maps/api/place/details/json?placeid=". $result->place_id ."&key=XXXX";
$placesearchresults = json_decode(file_get_contents($getplacedetails));
var_dump($placesearchresults); // shows all 5 results
}
var_dump($placesearchresults); // shows all 1 result (outside loop).
You have to change:
$placesearchresults = json_decode(file_get_contents($getplacedetails));
to:
$placesearchresults[] = json_decode(file_get_contents($getplacedetails));
Because in your current code you overwrite the value of $placesearchresults
every time, so that's also why at the end of the loop (outside) you only have 1 result. So to get every value outside of the loop we make a array out of: $placesearchresults
and add every value with []
to the array
Also that you have something to read :D See here under 'Creating/modifying with square bracket syntax ': http://php.net/manual/en/language.types.array.php
And a little quote out of that:
An existing array can be modified by explicitly setting values in it.
This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]).
$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type
If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize variable by a direct assignment.