美文网首页
PHP执行递归报错Segmentation fault排查笔记!

PHP执行递归报错Segmentation fault排查笔记!

作者: DragonersLi | 来源:发表于2021-09-17 01:31 被阅读0次

执行脚本,递归查询用户上级ID,然后更新到用户关系表,执行到367168时,报错Segmentation fault。意思是:段错误就是指访问的内存超过了系统所给这个程序的内存空间

[root@test]# php think test
Segmentation fault

查询367168上级是342668,342668的上级是367168死循环了。

ID upper
342668 367168
367168 342668
<?php
declare (strict_types = 1);

namespace app\common\command;

use app\common\model\{User as UserModel, UserUpper as UserUpperModel}; 
use think\console\{Command,Input,Output};
use think\console\input\{Argument,Option};  
class Test extends Command
{
    protected function configure()
    {

        $this->setName('test')->setDescription('php think test 测试'); // 指令配置
    }

   //生成器
    public static function generateData($data = [])
    {
        foreach($data as $k=>$v){
            yield $v;
        }
    }

    protected function execute(Input $input, Output $output)
    {
        set_time_limit(0);
        ini_set('memory_limit','1024M');

        UserUpperModel::field('uid,pid')->where('uid','>',342667)->chunk(10000,function($data){
            foreach(self::generateData($data) as $k=>$v){
                $pid = self::digui($v->uid);
                if(is_array($pid)){
                    $pid = implode(',',$pid);
                    $pid =  ','.$pid.',';
                }

                if($v->pid != $pid){
                    $res = UserUpperModel::where(['uid'=>$v->uid])->update(['pid'=>$pid]);
                    $msg =  "{$v->uid}上级ID由   ({$v->pid})   变更成   ({$pid})    结果:";
                    $msgs =($res ? "success\n":"error\n");
                    dlog('upper',$msg.$msgs);
                    echo $msg.$msgs;
                }else{
                    echo "{$v->uid}上级{$v->pid}---{$pid}\n";
                }
            }

        },'uid');
        exit('脚本执行完毕');
    }


    /**
     * 递归返回用户所有上级数组
     * self::digui(367168);
     * @param int $id
     * @param array $result
     * @return array
     */
    protected static function digui($id = 0,&$result =[]){

        $pid = UserModel::where(['id'=>$id])->value('upper');

        if($pid && $id !=$pid){
            $result[] = $pid;
            self::digui($pid,$result);
            return $result;
        }


    }
}

相关文章

网友评论

      本文标题:PHP执行递归报错Segmentation fault排查笔记!

      本文链接:https://www.haomeiwen.com/subject/krizrxtx.html