【问题标题】:Getting value from function and adding outside of for loop从函数中获取价值并在 for 循环之外添加
【发布时间】:2017-01-15 05:36:49
【问题描述】:

我有以下几点:

public function go(){
            for($x=0;$x<=31;$x++) {
                $this->get_answerrules($x);
                $DoneTime+=$DoneTime;
            }
            echo $gmdate("i:s", $DoneTime);;
        }

和

public function get_answerrules($x){
 ...
 ...
 ... 
        if($response = $this->request($data)){
            $obj = json_decode($response,true); 
                foreach($obj as $file) {
                        $Time += $file['batch_dura'];
                }
                $DoneTime = $Time;
                return $DoneTime;
       }else{}  
}

如何从 31 个 for 循环周期中获取值并将它们相加?

现在我的结果是空白的。

【问题讨论】:

  • 因为你不知道变量的作用域。

标签: php for-loop return return-value


【解决方案1】:

您没有使用方法调用的结果:

public function go(){
    for($x=0;$x<=31;$x++) {
        $this->get_answerrules($x);
        $DoneTime+=$DoneTime;
    }
    // The below won't work as `$gmdate` is not in the scope of the method.
    echo $gmdate("i:s", $DoneTime);;
}

应该是这样的:

public function go() {
    // Initialize the variable
    $DoneTime = 0;
    for($x = 0; $x <= 31; $x++) {
        $DoneTime += $this->get_answerrules($x);
    }
    echo $gmdate("i:s", $DoneTime);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 2017-09-30
    相关资源
    最近更新 更多