【问题标题】:Access array values outside of function in PHP在 PHP 中访问函数之外的数组值
【发布时间】:2014-10-01 16:54:08
【问题描述】:

我正在尝试访问为它们分配值的函数之外的变量。我认为最好的方法是将它们放入一个数组中,但似乎无法弄清楚如何在我的代码中的其他地方访问它们。我的功能如下:

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' ?>

【问题讨论】:

  • 回声 $return[like_count] ??
  • 将返回值赋给一个变量。所以:$output = getYouTubeMeta($post_id);。无论函数中的return'd 是什么,都将放在$output 变量中。然后,您可以像访问任何其他数组一样访问该返回值。 $output['like_count'].
  • 谢谢@JonathanKuhn。正是我正在寻找的答案。我现在可以访问所有值。

标签: php arrays variables


【解决方案1】:

首先将函数的结果分配给一个变量:

$result = getYouTubeMeta($post_id);

这将遍历您的数组并回显键及其值。

<?php
foreach($result as $key=>$value) {
  echo "Key=" . $key . ", Value=" . $value . "<br>";
}
?> 

如果你只想要一个特定的值,你可以使用:

echo $result['like_count'];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-22
    • 2013-02-11
    • 2011-02-21
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    相关资源
    最近更新 更多