使用数组创建WHERE条件

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 user friendly because there will be another person using this code.

What is the best way to do this?

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);
}

If you can change the format of the array, just use an associative array. For example:

array(

    "usuario" => "john" //etc.

);

Then you can take advantage of the key function in PHP to avoid your even index checking in the loop, or even change your loop to:

foreach ($params as $key => $value)
$query = "SELECT * FROM `funcionarios` WHERE ";
$wheres = array();

foreach ($paramas as $key => $val) {
    $wheres[] = "`$key`='$val'";
}

$query .= implode(' AND ', $wheres); // $query is now "SELECT * FROM `funcionarios` WHERE `myKey`='myValue' AND `otherkey`='otherval'";

That should work

Generate a new proper associative array from the original. Then it's much easier.

$arr = array("key1", "value1", "key2", "value2", "key3", "value3");
$newArr = array();
for ($i = 0; $i < count($arr); $i += 2) {
    $newArr[$arr[$i]] = $arr[$i + 1];
}

Then using foreach you can build your query.