0

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);
}
7
  • which array do you want to merge? Commented Jul 5, 2017 at 18:21
  • do u want to store all data in $std array? Commented Jul 5, 2017 at 18:21
  • where are the arrays to merger =???? Commented Jul 5, 2017 at 18:21
  • @RAUSHANKUMAR: Yes, I want to store all data in $std array. and i want it outside foreach loop . Commented Jul 5, 2017 at 18:23
  • @MuhammadUsman : I want to merge $std array . Commented Jul 5, 2017 at 18:24

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.