php中的变量范围外函数

时间:2014-04-01 11:12:54

标签: php

我有以下情景

在查找功能中,我有到达变量,我想获得$ reach变量中的所有$ follower值。

下面的代码给出了follwer的最后一个值,而不是all的总和。臭虫在哪里?

function x()
{        
    lookup($tweetid,$connection);    
}

function lookup($tweetid,$connection)
{
    $tweets5 = $connection->get("https://api.twitter.com/1.1/statuses/retweets/".$tweetid.".json?count=1");
    $json = json_encode($tweets5);
    foreach($tweets5 as $item)
    {
        $text = $item->text;
        $user_id = $item->user->id;
        $name = $item->user->name;
        $follower = $item->user->followers_count;

        $reach + = $follower; //This does not work
        // $reach = $raech + $follower; //This does not work
        $friend = $item->user->friends_count;
        echo  "Text : $text <br>  ID : $user_id <br> Name : $name <br> Follower : $follower <br> Friends : $friend <br> ---";
    }
    echo "<br> RT reach : $reach"; //This does not give some of folloewer count
}

3 个答案:

答案 0 :(得分:1)

尝试在foreach循环

之前声明变量$ reach = 0

答案 1 :(得分:0)

您需要先在$reach循环之外声明foreach变量

$reach = 0;
foreach($tweets5 as $item)
    {
        $text = $item->text;
..........
...

答案 2 :(得分:-1)

只需在foreach循环外声明$reach=0