记一次php的循环递归的低级错误

背景

出发点是为了减少一次性查询的数据量,做了一个while循环,然后当不符合条件的时候,把while循环break掉

错误的做法

 $openIds = $this->getUnionIdByOpenId();
      \Log::info(json_encode($openIds));
        while ($openIds != null){
            $app = app('wechat.official_account');
            $users = $app->user->select($openIds);
            $list = [];
            foreach ($users["user_info_list"] as $user){
                $list[] = [
                    'open_id' => $user['openid'],
                    'union_id' => $user['unionid'],
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now()
                ];
            }
            \DB::table('official_account')->insert($list);
            $this->insertAccount();
        }
  • 在while里头写递归,是不会生效的,while会一直执行里头的循环体,且上述代码并不会break掉while的循环,因此会不断的执行写库的操作

正确的做法

public function insertAccount(){
        while (1){
            $openIds = $this->getUnionIdByOpenId();
            \Log::info(json_encode($openIds));
            if (count($openIds) > 0){
                $app = app('wechat.official_account');
                $users = $app->user->select($openIds);
                $list = [];
                foreach ($users["user_info_list"] as $user){
                    $list[] = [
                        'open_id' => $user['openid'],
                        'union_id' => $user['unionid'],
                        'created_at' => Carbon::now(),
                        'updated_at' => Carbon::now()
                    ];
                }
                \DB::table('official_account')->insert($list);
            }else{
                break;
            }
        }
        echo "执行完毕";
        return;
    }
  • 正确的操作应该如上面这段代码,在循环体内做判断,并在合适的时候讲循环break掉
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 我曾读过热血的西游,看过充满爱情与美好的西游!西游似乎是一个永远都不会过时的词语,它的存在教育了数代人。...
    艾牙阅读 374评论 0 1
  • LeicaXue阅读 178评论 0 0