How to return a table field in a one dimensional array with an active code-ignitor write query

I am retrieving user role ids from user_roles table for login. A user can have multiple roles and I am getting the result in a multidimensional array. I am using a foreach loop to return role_ids in a single array for use in another IN clause of a query. Is there a way in code-ignitor to get the role ids in a one dimensional array. Here's what I've done so far:

Modal class Function for getting 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 returned array I am getting:

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

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

)

      

I need to pass the above returned array to another SQL IN expression because I need to manually modify the array like:

$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 returned array I am getting:

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

      

+3


source to share


2 answers


You can use array_column 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 on the controller

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

      

+3


source


Just use it like

$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 will cause the array to be



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

)

      

This way you can easily pass this value in the expression IN

+1


source







All Articles