我可以通过不同的方式重构嵌套循环吗?

时间:2016-06-21 19:19:26

标签: php loops refactoring

所以我有这个嵌套的while循环,我试图重构它并使它更具可读性,而且,我有点担心服务器超时(我还没有,但仍然),我不知道我希望我的服务器暂停一段时间(即使这还没有发生)。也许我错了,这里的一切都很好,但只是想确保我不犯错误,我将来会后悔..

while (count($columns)) {
    $columns = array_values($columns);
    $counter = 0;
    $row = new Row;
    $columnsCount = count($columns);

    while ($counter < $columnsCount) {
        $column = $columns[$counter];
        if ($row->hasSpaceFor($column)) {
            $row->add($column);
            unset($columns[$counter]);
        }
        $counter++;
    }

    $rows[] = $row;
}

我玩弄它并且走得很远:

while (count($columns)) {
    $columns = array_values($columns);
    $counter = 0;
    $row = new Row;
    $columnsCount = count($columns);

    $this->addColumns($columns, $counter, $columnsCount, $row);

    $rows[] = $row;
}

protected function addColumns(&$columns, $counter, $columnsCount, &$row)
{
    while ($counter < $columnsCount) {
        $column = $columns[$counter];
        if ($row->hasSpaceFor($column)) {
            $row->add($column);
            unset($columns[$counter]);
        }
        $counter++;
    }
}

0 个答案:

没有答案