简体   繁体   中英

Codeigniter active record return single array

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;

    }

result array

[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
       )

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

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 
)

Replace $form_titles[] = $form_names; with $form_titles[] = $form_names["form_text"];

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM