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
.
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
)
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);
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);
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