I'm trying to access variables outside of my function that assigns values to them. I thought the best way would be to put them into an array but cannot seem to figure out how to access them elsewhere in my code. My function is as follows:
function getYouTubeMeta( $post_id ) {
$video_id = get_post_meta( get_the_ID(), 'rfvi_video_id', true );
$api_key = "*********************";
$url = "https://www.googleapis.com/youtube/v3/videos?part=snippet,contentDetails,statistics&id=" . $video_id . "&key=" . $api_key;
$json = file_get_contents($url);
$json_data = json_decode($json);
$time_stamp = $json_data->items[0]->contentDetails->duration;
function duration($time_stamp) {
$di = new DateInterval($time_stamp);
return $di->format('%i:%S');
}
$youtube_duration = duration($time_stamp);
$like_count = $json_data->items[0]->statistics->likeCount;
$dislike_count = $json_data->items[0]->statistics->dislikeCount;
$view_count = $json_data->items[0]->statistics->viewCount;
$comment_count = $json_data->items[0]->statistics->commentCount;
$youtube_meta = array('like_count', 'dislike_count', 'view_count', 'comment_count', 'youtube_duration');
$result = compact($youtube_meta);
return $result;
}
If I use print_r($result); I get:
Array ( [like_count] => 2954 [dislike_count] => 37 [view_count] => 271763 [comment_count] => 385 [youtube_duration] => 3:16 )
I need to be able to echo out each key value independently in my code. Something along the lines of:
<?php echo 'returned_like_count_value' ?>
First assign the results of your function to a variable:
$result = getYouTubeMeta($post_id);
This would loop through your array and echo out the keys and their values.
<?php
foreach($result as $key=>$value) {
echo "Key=" . $key . ", Value=" . $value . "<br>";
}
?>
If you just want a particular value you can use:
echo $result['like_count'];