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

2018-12-24  本文已影响0人  路过的人儿

背景

出发点是为了减少一次性查询的数据量,做了一个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();
        }

正确的做法

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;
    }
上一篇下一篇

猜你喜欢

热点阅读