PHP yield

在php语法中,当foreach几千万以上的数据时,往往会内存溢出,此时就可以用生成器yield,yield大大降低了内存的开销,使用方式如下。不懂的可以看看官方文档

function main()
    {
        foreach ($this->test() as $val) {
            var_dump($val);
        }
    }
function test()
 {
        $tt = 10000000;
        for ($i = 1;$i <= $tt; $i++) {
            yield $i;
        }
    }

也可以自己指定键名

public function main()
    {
        foreach ($this->test() as $key => $val) {
            echo "
";
            var_dump($key);
            var_dump($val);
        }
    }
    private function test()
    {
        $typeAll = [1,2,3];
        foreach ($typeAll as $type) {
            $rewardData = LoginRewardTransferLogModel::getInstance()->getLists(['type' => $type]);
            if ($rewardData) {
                foreach ($rewardData as $key => $v) {
                    $id[] = $v['uid'];
                    $info = BackflowUserModel::getInstance()->getInfoByGid($v['gid']);
                    $tmp['platform'] =   $info ? $info['platform'] : '';
                    $tmp['last_version'] =  $info ? $info['last_version'] : '';
                    $tmp['gid'] = $info['gid'];
                    yield $v['uid'] => $tmp;
                }
            }
        }
    }
PHP yield_第1张图片

参考:

https://www.cnblogs.com/tingyugetc/p/6347286.html

http://www.php.net/manual/zh/language.generators.overview.php

你可能感兴趣的:(php)