Reputation: 1491
im returning data back from my db using codeigniter's database class , is there anyway I can put it into the same array without having to do additional array_merge logic after the loop completes?
foreach ($saved_forms[0] as $key => $value) {
$this->db->select('form_text');
$this->db->from('form_labels');
$this->db->where('form_label', $key);
$query = $this->db->get();
$form_names = $query->result_array();
$form_titles[] = $form_names;
}
[4] => Array
(
[0] => Array
(
[form_text] => Participant Name
)
)
[5] => Array
(
[0] => Array
(
[form_text] => Date of Birth
)
)
What I want:
[0] => Array
(
[form_text] => Participant Name
[form_text] => Date of Birth
)
Upvotes: 1
Views: 7490
Reputation: 47972
Most succinctly, fetch all qualifying rows associated with the $saved_forms[0]
keys, then return the form_labels
column from that array of zero or more objects. This will return a flat, indexed array of form_text
values.
return array_column(
$this->db
->where_in('form_label', array_keys($saved_forms[0]));
->get('form_labels')
->result(),
'form_text'
);
Upvotes: 0
Reputation: 8771
When Running PHP 5 >= 5.5.0 you can achieve this with the built-in function array_column()
$form_names = $query->result_array();
$my_array = array_column($form_names, 'form_text');
Produces:
Array (
[0] => Participant Name
[1] => Date of Birth
)
Upvotes: 2
Reputation: 54639
Try this
$query = $this->db->select('form_text')
->from('form_labels');
->where_in('form_label', array_keys($saved_forms[0]));
->get();
foreach( $query->result as $label){
$form_titles[] = $label->form_text;
}
It will produce a single array with the texts
Upvotes: 3
Reputation: 64476
Simple use the where_in()
use foreach to get all the keys and run your query in a go and get rid of running query again and again
$keys=array();
foreach ($saved_forms[0] as $key => $value) {
$keys[] = $key;
}
$this->db->select('form_text');
$this->db->from('form_labels');
$this->db->where_in('form_label', $keys);
// or $this->db->or_where_in();
$query = $this->db->get();
$form_names = $query->result_array();
Upvotes: 1
Reputation: 3435
Replace $form_titles[] = $form_names;
with $form_titles[] = $form_names["form_text"];
Upvotes: 1