我使用codeigniter的数据库类从我的数据库返回数据,无论如何我可以把它放到同一个数组中,而不需要在循环完成后再执行额外的array_merge逻辑吗?
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
)
)
我想要的是什么:
[0] => Array
(
[form_text] => Participant Name
[form_text] => Date of Birth
)
答案 0 :(得分:3)
试试这个
$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;
}
它将生成带有文本
的单个数组答案 1 :(得分:2)
运行PHP 5> = 5.5.0时,您可以使用内置函数array_column()
$form_names = $query->result_array();
$my_array = array_column($form_names, 'form_text');
制作:
Array (
[0] => Participant Name
[1] => Date of Birth
)
答案 2 :(得分:1)
将$form_titles[] = $form_names;
替换为$form_titles[] = $form_names["form_text"];
答案 3 :(得分:1)
简单地使用where_in()
使用foreach获取所有密钥并一次性运行查询并一次又一次地摆脱运行查询
$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();