1

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 a v 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 ?

hakre
  • 178,314
  • 47
  • 389
  • 754
Nishant Jani
  • 1,890
  • 8
  • 28
  • 39

4 Answers4

2

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
}
Loken Makwana
  • 3,498
  • 1
  • 18
  • 14
  • noo, that is completely wrong , the 124 in the description is just an instance i want to check for a list of user id – Nishant Jani Aug 13 '12 at 07:43
1

As the other comments are saying, there are better ways to do this but as you insist to do it like this, just transform the id into an array to match the result array structure:

in_array(array('id' => 124),$returned_array)
Telémako
  • 573
  • 2
  • 9
1

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

Yan Berk
  • 13,978
  • 9
  • 52
  • 52
0

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.

alex
  • 438,662
  • 188
  • 837
  • 957