逐个读取数组值where子句

时间:2014-05-18 09:43:11

标签: php arrays codeigniter

这是我的控制器

$data['lvl0'] = $this->web_model->menulvl0();
if ($data['lvl0'] != ''){
  foreach($data['lvl0'] as $l0){
     $data['id'] = $l0['id'];
 $data['name'] = $l0['name'];
 $temp = explode(" ",$l0['id']);
 $data['lvl1'] = $this->web_model->menulvl1($temp);
 }
}

当我print_r($ temp)时。结果是:

Array ( [0] => 10 ) 
Array ( [0] => 20 ) 
Array ( [0] => 30 ) 
Array ( [0] => 40 )

我想将该数组放入查询中。这是我的疑问:

SELECT id, name FROM A where level = 1 and parent = '$array'

我希望逐个读取该数组。所以,查询将是:

SELECT id, name FROM A where level = 1 and parent = '10'

然后

SELECT id, name FROM A where level = 1 and parent = '20'

等等。

怎么做?

2 个答案:

答案 0 :(得分:1)

使用foreach语句对数组进行排序:

foreach($array as $val)
{
    $query="SELECT id, name FROM A where level = 1 and parent = '".$val."'";
}

您可以在那里运行它,也可以只进行查询。

或者,您可以使用implodein声明:

$vals=implode(",",$array);
$query="SELECT id, name FROM A where level = 1 and parent in(".$vals.")";

答案 1 :(得分:0)

您可以使用CI's active record

执行此操作
$query=$this->db->select('id, name')
->from('A')
->where('level',1)
->where_in('parent',$array)
->order_by('parent')
->get();

$result=$query->result();