drtkyykai004574380 2014-10-01 16:54
浏览 66

在PHP中访问函数外部的数组值

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' ?>
  • 写回答

1条回答 默认 最新

  • dongru2019 2014-10-01 17:00
    关注

    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'];
    
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?