Reputation:
I have this function that returns a json object:
function getMyFbEvents() {
global $facebook;
try {
$fb_events = $facebook->api('/me/events/');
foreach ($fb_events["data"] as $fb_event_data) {
$event_info = json_decode(file_get_contents('https://graph.facebook.com/' . $fb_event_data['id'] . '/?access_token=' . $facebook->getAccessToken()));
return $event_info;
}
} catch (FacebookApiException $e) {
error_log($e);
$fb_events = null;
return null;
}
}
Now if I want to call that object from another page of the script by calling the relative function, how do I do it?
I mean if I want to loop now $event_info
as if it I was inside that function and get each given data, is there a way?
Maybe it may sound a bit "too much" :)
Upvotes: 0
Views: 69
Reputation: 24645
First of instead of returning from within the loop you need to accumulate all of the values then return
function getMyFbEvents() {
global $facebook;
try {
$fb_events = $facebook->api('/me/events/');
$eventDetails = array();
foreach ($fb_events["data"] as $fb_event_data) {
$event_info = json_decode(file_get_contents('https://graph.facebook.com/' . $fb_event_data['id'] . '/?access_token=' . $facebook->getAccessToken()));
$eventDetails[] = $event_info;
}
return $eventDetails;
} catch (FacebookApiException $e) {
error_log($e);
$fb_events = null;
return null;
}
}
Then when you want to use it just say (make sure you include_once the file that implements getMyFbEvents if it is in a different php file.)
$events = getMyFbEvents();
forearch($events as $event){
echo $event->description;
}
On a side note using the global
keyword is considered bad practice. A cleaner implementation would just pass in the $facebook variable as a parameter to the function
function getMyFbEvents($facebook) {
try {
//..... the rest of your function
Then to call just
$var = getMyFbEvents($facebook);
Upvotes: 1