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 ?

4
  • 3
    How about selecting from the database WHERE id = 124? Commented Aug 13, 2012 at 7:35
  • nooo , there are a list of id that i need to choose and then check Commented Aug 13, 2012 at 7:42
  • 1
    I think this stackoverflow.com/questions/4128323/… will help you Commented Aug 13, 2012 at 7:45
  • $reccs does not equal $recs Commented Jul 14 at 1:31

4 Answers 4

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

noo, that is completely wrong , the 124 in the description is just an instance i want to check for a list of user id
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

Comments

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)

Comments

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.

4 Comments

yep my IDE says , its not compatible
@user1537158 Sorry, I'd forgotten to pass the array to array_map(). Try it now.
what is $val , im sorry i dont follow :(
@user1537158 That will be each sub array in your array.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.