How can I receive indexed array after mysql query? Or is there any method to convert $this->db->get() into mysql resource? Or convert associative array to indexed?
-
What DB extension are you using? PDO, mysqli etc?DaveRandom– DaveRandom2011-10-24 15:13:24 +00:00Commented Oct 24, 2011 at 15:13
-
3Also, why? What do you need to do that requires the array to be indexed, not associative?DaveRandom– DaveRandom2011-10-24 15:14:04 +00:00Commented Oct 24, 2011 at 15:14
-
You can not convert PHP resources. They need to exist.hakre– hakre2011-10-24 17:16:57 +00:00Commented Oct 24, 2011 at 17:16
3 Answers
PHP has a function array_values() that will return an array of just the values.
Comments
Example on converting codeigniter result_array to indexed Array:
$query = $this->db->query("SELECT `tag_id` FROM `tags`");
$arr = $query>result_array();
print_r($arr); //codeigniter default result array
//Output:
Array
(
[0] => Array
(
[tag_id] => 1
)
[1] => Array
(
[tag_id] => 3
)
)
Now If You want to convert above array to indexed Array then you have to use array_column() function which convert it associative array to indexed array by taking array key as argument see Below for example:
$query = $this->db->query("SELECT `tag_id` FROM `tags`");
$tags = $query>result_array();
$arr = array_column($tags, "tag_id");
print_r($arr); //converted indexed array
//Output:
Array
(
[0] => 1
[1] => 3
)
Comments
It looks like you might be using PHP CodeIgniter. 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.