我试图访问我的函数之外的变量,为它们赋值。我认为最好的方法是将它们放入一个数组,但似乎无法弄清楚如何在我的代码中的其他地方访问它们。我的功能如下:
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;
}
如果我使用print_r($ result);我明白了:
Array ( [like_count] => 2954 [dislike_count] => 37 [view_count] => 271763 [comment_count] => 385 [youtube_duration] => 3:16 )
我需要能够在代码中独立回显每个键值。有点像:
<?php echo 'returned_like_count_value' ?>
答案 0 :(得分:0)
首先将函数的结果赋给变量:
$result = getYouTubeMeta($post_id);
这将遍历您的数组并回显键及其值。
<?php
foreach($result as $key=>$value) {
echo "Key=" . $key . ", Value=" . $value . "<br>";
}
?>
如果您只想要特定值,可以使用:
echo $result['like_count'];