简体   繁体   中英

How to merge array inside foreach loop?

How to merge array inside foreach loop in php ?

Here is my Code:

$subjects = $this->db->order_by('id','desc')->get_where('tbl_class_management', array('status'=>'1','teacher_id'=>$this->teacher->id))->result();
foreach ($subjects as $key => $s) {
   $std = $this->db->get_where('tbl_student', array('batch'=>$s->batch,'semester'=>$s->semester,'faculty'=>$s->faculty))->result();
debug($std);
}

if you want to store all your data in $std array by iterating over $subjects array, declare your $std array outside the loop then sipmly push data in this one by one when you iterating over loop, use like this

$subjects = $this->db->order_by('id','desc')->get_where('tbl_class_management', array('status'=>'1','teacher_id'=>$this->teacher->id))->result();
$std=[];
foreach ($subjects as $key => $s) {
    $std[] = $this->db->get_where('tbl_student', array('batch'=>$s->batch,'semester'=>$s->semester,'faculty'=>$s->faculty))->result();
}
$std = json_decode(json_encode($std,true),true);
print_r($std);

The general formula for merging two arrays is as follows (merging $array_m into $array_o):

foreach($array_m as $key=>$value){ 
    $array_o[$key] = $value;
}

$array_o would now contain all of the elements of $array_m

EDIT: I just noticed in your post that you seem to want to use the array_merge function. You could also do the following:

$array_o = array_merge($array_o, array_m);

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