简体   繁体   中英

Use function only once inside a foreach loop

I have a MySQL DB field populated with some data. 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 ($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. This is how show_clean() looks:

    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.

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. 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 {
        // ...
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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