循环不会遍历整个数组

时间:2017-05-03 14:12:22

标签: php loops

我需要将每个Laravel模型的内容保存为json。这个函数应该提供一个很好的快捷方式:

public function ni()
{
    $filenames = array();
    $errors = array(); 

    foreach(glob(__DIR__.'\..\..\..\Models\CounterPoint\*') as $file) {
        $filename = preg_replace('/C:[\D]*\\\\/', '', $file);
        $filename = preg_replace('/.php/', '', $filename);
        if ($filename == 'CompositeKey' | $filename == 'Custom') {
            continue;
        }
        $filenames[] = $filename;
        unset($filename);
    }

    $len = count($filenames);
    echo "We have $len files.<br/><br/>";

    for ($i=0; $i < $len; $i++) {
        echo "On iteration $i, file is $filenames[$i]<br/>";
        $model = '\App\Models\CounterPoint\\'.$filenames[$i];
        if ( $obj = $model::first() ) {
            $path = __DIR__.'\..\..\..\..\database\factories\seed_data\\'.$filenames[$i].'.json';
            file_put_contents($path, $obj);
            unset($obj);
        } else {
            $errors[] = $filenames[$i];
        }
    }
}

if (!empty($errors)) {
    foreach ($errors as $e) {
        print_r($e)."<br>";
    }
}

但是,输出如下:

We have 102 files.
On iteration 0, file is ArAdjTrx
On iteration 1, file is ArCategCod
On iteration 2, file is ArCust
On iteration 3, file is ArCustProfCod
On iteration 4, file is ArMergeCust
On iteration 5, file is ArMergeCustGrp
On iteration 6, file is ArShipAdrs
On iteration 7, file is ArTaxCod
On iteration 8, file is ArTaxCodAuth
On iteration 9, file is CsosEcomConfigAttr
On iteration 10, file is CsosEcomConfigVal
On iteration 11, file is DbCtl
On iteration 12, file is DmSalStrItemDay
On iteration 13, file is EcCateg

没有抛出错误,到目前为止创建的文件是正确的。我想知道为什么它停在13而不是$len。 (查看目录,可以看到还有更多文件。)另请注意$errors必须为空。

我希望循环触及每个文件,从ArCategCodUsrItemImages

0 个答案:

没有答案