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
)
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() );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With