Execute the function once get the return and use in a codeIgniter loop

0

Hello

I'm having trouble retrieving the return of a model and using it in a foreach, without the function being executed again several times ...

How can I do to get the return and use this same return 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
        );
            }
    
asked by anonymous 18.04.2016 / 21:46

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 ... Embrace ...

    
27.04.2016 / 07:26