hello members a anomaly in codeigniter im noticing
in my model im querying the database to get a list of user_id ONLY
$recs = $this->db->query('select id from users');
that was easy, but i want to return the result as an array
so i do
$reccs->result_array();
but now in my controller i want to check for in_array(124,$returned_array); this is not successful because codeigniter has encapsulated the array of id into av big outer array something like this
Array ( [0] => Array ( [id] => 0 ) [1] => Array ( [id] => 11 ) [2] => Array ( [id] => 29 ))
how can i use the in_array php function to check only id ?
OR
how can i built a plain array just to store id something like
$demo = array();
foreach($recs as $r)
$demo = array($r->id);
Any suggestions ?
If you want to check whether user is there or not you should make a count query.
$this->db->where('id',124);
$count = $this->db->count_all_results('users');
if($count) {
// found
} else {
// not found
}
正如其他评论所说,有更好的方法可以做到这一点但是你坚持这样做,只需将id转换为数组以匹配结果数组结构:
in_array(array('id' => 124),$returned_array)
You can loop the result set and generate a ne w array and make use of it. Below is the code which may be usefull
$i=0;
foreach($reccs->result_array() as $values)
{
$new_array[]=$values[$i]['id'];
$i++;
}
make use of $new_array for in_array comparision
You could use array_map()
to pluck that key from each sub array. Then, in_array()
will work as per normal.
$found = in_array(124,
array_map(function($val) { return $val['id']; },
$returned_array
)
);
If you don't have >= PHP 5.3, then replace the anonymous function with a named one.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.