简体   繁体   English

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

[英]How to merge array inside foreach loop?

How to merge array inside foreach loop in php ? 如何在php中的foreach循环中合并数组?

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数组将所有数据存储在$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);

The general formula for merging two arrays is as follows (merging $array_m into $array_o): 合并两个数组的一般公式如下(将$ array_m合并到$ array_o中):

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

$array_o would now contain all of the elements of $array_m $ array_o现在将包含$ array_m的所有元素

EDIT: I just noticed in your post that you seem to want to use the array_merge function. 编辑:我只是在您的帖子中注意到您似乎想使用array_merge函数。 You could also do the following: 您还可以执行以下操作:

$array_o = array_merge($array_o, array_m);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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