Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Codeigniter: get all values from single column as array

Here is my query to get a single column from t

$sql = "SELECT `id` FROM `loc8_groups`";
 $query = $this->db->query($sql);
 print_r($query>result());

Its produce array result like this way.

Array
(
    [0] => stdClass Object
        (
            [id] => 1
        )

    [1] => stdClass Object
        (
            [id] => 2
        )

    [2] => stdClass Object
        (
            [id] => 3
        )

)

But i want result as single associative array that contains all the ids.

like image 783
shellakkshellu Avatar asked Aug 03 '16 08:08

shellakkshellu


3 Answers

CodeIgniter's DB implementation doesn't support indexed result arrays, you have to choose between object or associative array.

This is done to make your queries more maintainable, as returning numeric indexes are harder to debug and maintain.

CodeIgniter Docs - database results

but you can do it, i am suggesting very useful inbuilt function array_column() for you

array_column() returns the values from a single column of the input, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.

it will convert your codeigniter's associative array to indexed array.

$sql = "SELECT `id` FROM `loc8_groups`";
$query = $this->db->query($sql);
$array = $query->result_array();
$arr = array_column($array,"id");
print_r($arr);

it will produce array as below:

Array
(
   [0] => 1

   [1] => 2

   [2] => 3

)
like image 191
Haritsinh Gohil Avatar answered Nov 20 '22 05:11

Haritsinh Gohil


Try this code:

$sql = "SELECT `id` FROM `loc8_groups`";
$query = $this->db->query($sql);
$array1=$query>result_array();
$arr = array_map (function($value){
    return $value['id'];
} , $array1);
 print_r($arr);
like image 25
Lakremon Avatar answered Nov 20 '22 06:11

Lakremon


use mysql group_concat, to avoid foreach or using array_map,etc.

$sql = "SELECT group_concat(id separator ',') as id FROM `loc8_groups`";
$query = $this->db->query($sql);
$array1 = $query->row_array();
$arr = explode(',',$array1['id']);

print_r($arr);
like image 3
Golduno Support Avatar answered Nov 20 '22 04:11

Golduno Support