简体   繁体   English

在foreach循环内只能使用一次功能

[英]Use function only once inside a foreach loop

I have a MySQL DB field populated with some data. 我有一个MySQL DB字段,其中填充了一些数据。 I have an option in my script which cleans that field so I can add new fresh data to it without appending to the old stuff. 我在脚本中有一个选项可以清除该字段,因此我可以向其中添加新的新数据,而无需附加到旧内容。

However I am using a foreach loop which looks like this: 但是我正在使用一个foreach循环,如下所示:

            foreach ($model->filenames as $key => $model->filename) {
            $model->get_title($model->filename);
            $model->get_showTitle($model->titles);
            $model->get_number($model->titles);
            $model->get_host($model->urls[$key]);
            $model->source_title($model->titles);
            $model->get_season();
            if ($model->show_exist_batch()) {
                $model->show_clean(); //the method in question
                $model->show_update();
            } else {
                $model->show_add();
                $model->twitter();
            }

The thing is that I want show_clean() to only run ONCE. 问题是我希望show_clean()仅运行一次。 This is how show_clean() looks: 这是show_clean()的样子:

    public function show_clean() {
    if ($this->options->clean) {
        $query = "UPDATE jos_k2_items SET extra_fields = '', extra_fields_search = '' WHERE id = " . $this->item->id . "";
        $this->db->prepare($query);
        $this->db->query();
    }
}

$this->option->clean is set by a post variable in the constructor. $ this-> option-> clean由构造函数中的post变量设置。

Are there any clever ways of doing this or do i need to do it the long way? 有什么聪明的方法可以做到这一点吗?还是我需要很长的路要走?

Not sure how "clever" this is, but its one way that doesn't seem to be long. 不知道这有多“聪明”,但是它的一种方式似乎并不长。

Set a variable outside of your loop indicating that you have not cleaned, and only call clean if it hasn't been set yet. 在循环外设置一个变量,指示您尚未清理,并且仅在尚未设置时调用clean。 Once you clean the first, time, set your flag so it will not clean again. 第一次清洁后,请设置您的标志,这样它就不会再次清洁。

$cleaned = false;
foreach ($model->filenames as $key => $model->filename) {
    // ...
    if ($model->show_exist_batch()) {
        if (!$cleaned) {
            $model->show_clean();
            $cleaned = true;
        }
        $model->show_update();
    } else {
        // ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM