Run the function once take the Return and use in a codeIgniter loop

Asked

Viewed 341 times

0

Hello

I’m having trouble recovering the Return from a model and using it in a loop (foreach), without the function running again several times...

How can I take Return and use it several times?

Code for illustration:

    $valorModel = $this->model->funcao(); // recupera o return


    foreach ($var as $var2) {
        $array = array(
            'colunaDb' => $var2->item,
            'colunaDb' => $valorModel, // executa a função varias vezes
            'colunaDb' => $var2->item
        );
            }
  • It would be good to post part of the code to help in understanding...

  • posted a code to illustrate my problem

  • Did you return $query->result()? If you return only one element, for example, use $query->Rows->fieldName.

1 answer

0

An idea, do the following, within your model declare a private $var... a structure similar to this:

class Model {
    public $email;

    public function findEmailById($id){
        // ... função que busca no banco de dados, etc...
        $this->email = $retorno; // $retorno seria a variável com o resultado da sua query ou função. ao invés de usar um return $var.
    }

    public function getEmail(){
        return $this->email;
    }

}

Now on your controller, use your code like this:

$this->load->model('model');
$m = new Model();
$m->funcao();  // recupera o return

    foreach ($var as $var2) {
        $array = array(
            'colunaDb' => $var2->item,
            'colunaDb' => $m->getEmail(), // pega apenas o email já salvo pela função
            'colunaDb' => $var2->item
        );

Ready, simple and without repeating N times the function... Hug...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.