phparrayscodeigniteractiverecordwhere-clause

Pass every two elements of an index array as column => value parameters for CodeIgniter's where() method


My function receives a array as parameter:

array(6) {
  [0]=>
  string(7) "usuario"
  [1]=>
  string(4) "john"
  [2]=>
  string(5) "senha"
  [3]=>
  string(40) "7c4a8d09ca3762af61e59520943dc26494f8941b"
  [4]=>
  string(9) "pessoa_id"
  [5]=>
  string(1) "2"
}

What I need:

SELECT * FROM (`funcionarios`) WHERE `usuario` = 'john' AND `senha` = '7c4a8d09ca3762af61e59520943dc26494f8941b' AND `pessoa_id` = '2'

I need to create a WHERE with it, I'm using CodeIgniter and I came to this stupid but working solution:

foreach ($params as $x) {
    if ($pos % 2 == 0)
        $chave = $x;
    else
        $valor = $x;
    $pos++;
    if ($pos % 2 == 0)
        $this->db->where($chave, $valor);
    }

I'm trying to find something more developer-friendly because there will be another person using this code.

What is the best way to do this?


Solution

  • I think this it the best way if you can't change that array. IF you can, do so now, because it's really inelegant

    $data = array(
       "usuario" => "john",
       "senha" => "7c4a8d09ca3762af61e59520943dc26494f8941b",
       "pessoa_id" => 2
    );
    
    foreach($params as $x => $y) {
          $this->db->where($x, $y);
    }