dongquan8753 2018-12-13 06:25
浏览 56
已采纳

laravel:无法将对象属性推送到数组[复制]

I have stuck in a silly silly sample of code but i can't find solution. I have this code:

Route::get('/example', function(){
    $arr=[];
    Collection::all()->each(function($collection){
        $arr[]= $collection->id;
    });
    dd($arr);
}); 

and it returns to me an empty array all the time despite the fact that Collection:all() has objects inside. Can someone help me?

</div>
  • 写回答

1条回答 默认 最新

  • dpicx06888 2018-12-13 06:30
    关注

    In the each section you define function which make it with new scope for the variable.

    Try the use of PHP function as:

    Route::get('/example', function(){
        $arr=[];
        Collection::all()->each(function($collection) use (&$arr){
            $arr[]= $collection->id;
        });
        dd($arr);
    }); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部