如何在foreach循环中合并数组?

时间:2017-07-05 18:19:32

标签: php arrays codeigniter

如何在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);
}

2 个答案:

答案 0 :(得分:2)

如果要通过迭代$std数组将所有数据存储在$subjects数组中,请在循环外声明$ 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);

答案 1 :(得分:0)

合并两个数组的通用公式如下(将$ 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);