Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 672
Nick Avatar asked Mar 12 '26 23:03

Nick


1 Answers

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 {
        // ...
    }
}
like image 50
drew010 Avatar answered Mar 14 '26 12:03

drew010



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!