优化PHP代码

时间:2017-03-31 15:18:14

标签: php

有没有办法对此进行优化?

// Zählt die Anzahl an KWs
$sum = 0;
for ($i = 1; $i < 105; $i++) {
    $count = db_query('SELECT cw' . $i . ' FROM `prefix_projekteStep` WHERE kategoryid = ' . $row->id . ' AND id = ' . $rowStep->id.' AND jahr = '.$currentYear.' OR jahr = '.$nextYear.'');
    while ($rowStepC = db_fetch_object($count)) {
        $var = "cw" . $i;
        if ($rowStepC->$var === 1) {
            $sum += 1;
        }
    }
}    
echo $sum;

目前,脚本在通话中运行了大约104次,我称之为大约40次。完成需要很长时间。

2 个答案:

答案 0 :(得分:1)

如果我理解你想要做什么,这可能会奏效。运行它并回显SQL语句以查看它的外观:

# Make a character vector of the names of the columns we want to take the
# maximum over
target_columns = iris %>% select(-Species) %>% names
## [1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"

# Make a vector of dummy variables that will take the place of the real
# column names inside the interpolated formula
dummy_vars = sapply(1:length(target_columns), function(i) sprintf('x%i', i))
## [1] "x1" "x2" "x3" "x4"

# Paste those variables together to make the argument of the pmax in the
# interpolated formula
dummy_vars_string = paste0(dummy_vars, collapse=',')
## [1] "x1,x2,x3,x4"

# Make a named list that maps the dummy variable names (e.g., x1) to the
# real variable names (e.g., Sepal.Length)
dummy_vars_list = lapply(target_columns, as.name) %>% setNames(dummy_vars)
## $x1
## Sepal.Length
##
## $x2
## Sepal.Width
## 
## $x3
## Petal.Length
##
## $x4
## Petal.Width

# Make a pmax formula using the dummy variables
max_formula = as.formula(paste0(c('~pmax(', dummy_vars_string, ')'), collapse=''))
## ~pmax(x1, x2, x3, x4)

# Interpolate the formula using the named variables
library(lazyeval)
iris %>%
  mutate_(max_attribute=interp(max_formula, .values=dummy_vars_list)) %>%
  head(3)
##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species max_attribute
## 1          5.1         3.5          1.4         0.2  setosa           5.1
## 2          4.9         3.0          1.4         0.2  setosa           4.9
## 3          4.7         3.2          1.3         0.2  setosa           4.7

答案 1 :(得分:1)

当然数据库结构设计很差,所以应该优先考虑。

此外,如果没有更高层次的理解你想要达到的目标,很难给出一个全面的答案,但是考虑到可以从你的问题中的代码中收集的信息,你当然可以只是切换循环,选择你的SQL中的整行,并在嵌套的php循环中计算总和,将你的查询减少到1:

$count = db_query('SELECT * FROM `prefix_projekteStep` WHERE kategoryid = ' . $row->id . ' AND id = ' . $rowStep->id.' AND jahr = '.$currentYear.' OR jahr = '.$nextYear.'');

while ($rowStepC = db_fetch_object($count)) {
     for ($i = 1; $i < 105; $i++) {
         $var = "cw" . $i;
         if ($rowStepC->$var === 1) {
               $sum += 1;
         }
     }
}

但重构数据库应该被视为优先事项。