[英]How to merge array inside foreach loop?
如何在php中的foreach循環中合並數組?
這是我的代碼:
$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);
}
如果要通過遍歷$subjects
數組將所有數據存儲在$std
數組中,請在循環外聲明$ std數組,然后在遍歷遍歷循環時逐一逐個推送數據,請像這樣使用
$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);
合並兩個數組的一般公式如下(將$ array_m合並到$ array_o中):
foreach($array_m as $key=>$value){
$array_o[$key] = $value;
}
$ array_o現在將包含$ array_m的所有元素
編輯:我只是在您的帖子中注意到您似乎想使用array_merge函數。 您還可以執行以下操作:
$array_o = array_merge($array_o, array_m);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.