php递归循环,记一次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掉

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值