Umar Adil
Umar Adil

Reputation: 5277

How to return a table field in single dimensional array with code-igniter active record query

I am fetching user role ids from user_roles table for logged in user. A user can have multiple roles and I am getting the result in multi-dimensional array. I am using foreach loop to return the role_ids in single array to use in other query IN clause. Is there a way in code-ignitor to retrieve the role ids in single dimensional array. Here is what I did so far:

The Modal class Function to get the roles

$select_fields = 'ur.role_id AS role_id';

$this->db->select($select_fields, FALSE); 

$this->db->from('users_roles AS ur');   
$this->db->where('ur.user_id', $user_id);  
$query = $this->db->get(); 
if($query->num_rows())
{
    return $query->result_array(); 
}
return FALSE; 

The return array I am getting:

Array
(
    [0] => Array
        (
            [role_id] => 1
        )

    [1] => Array
        (
            [role_id] => 2
        )

)

I need to pass the above return array to other SQL IN Statement for I have to manually change the array as:

$select_fields = 'ur.role_id AS role_id';

$this->db->select($select_fields, FALSE); 

$this->db->from('users_roles AS ur');   
$this->db->where('ur.user_id', $user_id);  
$query = $this->db->get(); 
if($query->num_rows())
{
    $result = $query->result_array(); 
    $user_role_ids = array();
    foreach ($result as $key => $value) {
        $user_role_ids[]    = $value['role_id'];
    }
    return $user_role_ids;
}
return FALSE;

The return array I am getting:

Array
(
    [0] => 1
    [1] => 2
)

Upvotes: 3

Views: 1969

Answers (2)

Akshay Hegde
Akshay Hegde

Reputation: 16997

You can make use array_column function, if you have installed latest php

Like this

function somename()
{
  ...
  ...
  return array_column($query->result_array(),'role_id');  
}

OR

function somename()
{
  ...
  ...
  return array_map(function($_){return $_['role_id'];}, $query->result_array());
}

and ultimately you can call like on your controller

$this->db->where_in('some_fieldname', $this->somename() );

Upvotes: 3

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21422

Just use it as

$select_fields = 'group_concat(ur.role_id) AS role_id';

$this->db->select($select_fields, FALSE); 

$this->db->from('users_roles AS ur');   
$this->db->where('ur.user_id', $user_id);  
$query = $this->db->get(); 
if($query->num_rows())
{
    return $query->result_array(); 
}
return FALSE;

This'll result you an array as

Array
(
    [0] => Array
        (
            [root] => 1,2,3,4
        )

)

So this way you can easily pass that value within IN statement

Upvotes: 1

Related Questions