1

我使用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
       )
4

4 回答 4

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;
}

它将生成一个包含文本的数组

于 2013-09-06T19:57:09.723 回答
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 
)
于 2014-11-25T05:25:57.033 回答
1

替换$form_titles[] = $form_names;$form_titles[] = $form_names["form_text"];

于 2013-09-06T19:31:30.007 回答
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();
于 2013-09-06T19:35:41.163 回答