【问题标题】:PHP call by value returning less value to the main functionPHP按值调用向主函数返回较少的值
【发布时间】:2017-09-05 05:09:32
【问题描述】:

我有一个奇怪的问题,我编写了一个递归函数来从 facebook 获得更多结果。在被调用的函数(递归)中,我将值返回给主函数。在被调用的函数中,当我打印返回值时,它会显示确切的值(通常是 90 的数组大小)。但是在我打印返回值的主函数中,它总是更小(每次数组大小正好是50)。这是我的代码..

public function mainFunction(){
    $response = $fb->get('/me?fields=id,name,accounts', $useraccesstoken);    
    $userData = $response->getDecodedBody();
    $pages = $userData['accounts'];
    $pages = $this->getMorePages($pages);
}

public function getMorePages($pages){
    if(count($pages)>1 && isset($pages['paging']['next'])){
        $morePages = file_get_contents($pages['paging']['next']);
        $morePages = json_decode($morePages,true);
        foreach($morePages['data'] as $page){
            array_push($pages['data'],$page);
        }
        if(count($morePages)>1 && isset($morePages['paging']['next'])) {
            $pages['paging']['next']=$morePages['paging']['next'];
            $this->getMorePages($pages);
        }
        return $pages;
    }else{
        return $pages;
    }
}

我的代码有什么问题..?

【问题讨论】:

    标签: php function recursion laravel-5 call-by-value


    【解决方案1】:

    您正在使用递归函数,但没有使用内部调用返回的值...

    固定代码为:

    public function getMorePages($pages){
        if(count($pages)>1 && isset($pages['paging']['next'])){
            $morePages = file_get_contents($pages['paging']['next']);
            $morePages = json_decode($morePages,true);
            foreach($morePages['data'] as $page){
                array_push($pages['data'],$page);
            }
            if(count($morePages)>1 && isset($morePages['paging']['next'])) {
                $pages['paging']['next']=$morePages['paging']['next'];
    
                // Add return values to the main array
                //$pages += $this->getMorePages($pages);
                // For more support use array_merge function
                $pages = array_merge( $this->getMorePages($pages), $pages )
            }
            return $pages;
        }else{
            return $pages;
        }
    }
    

    【讨论】:

    • 上述 array_push() 方法的用途与 array_merge() 相同。
    • @RAUSHANKUMAR 但您不会在返回的递归数组上推送到数组...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多