Search code examples
phpcodeigniterarray-merge

What the best way to deal with codeigniter php array_merge, in a foreach?


I'm trying to list all students from schools whose school_location_id = 1, I'm connected to multiple school databases using codeigniter's USE. My challenge is that it is only listing students from the last school. Below is my code,

$schools = $this -> db->select('*')
    ->from('schools')
    ->where('schools.school_location_id', 1)
    ->get()->result_array();
foreach ($schools as $row) :
    $school_db_name = $row['school_db_name'];
    $this->db->query("use $school_db_name");  // here I switch school database, cause I'm connected to multiple school databasees
    $school_students = $this->db->select('*')
        ->from('school_students')
        ->get()->result_array();
endforeach;

$recipients = array_merge($school_students);

foreach ($recipients as $row) :
    echo $row['name'];
endforeach;

Solution

  • $school_students is being overwritten for every pass of your foreach-loop. One alternative is to simply add the results to an array like so:

        foreach($schools as $row):
                $school_db_name    =   $row['school_db_name'];
                $this->db->query("use $school_db_name");
                $school_students[]    =   $this->db->select('*')
                                        ->from('school_students')
                                        ->get()->result_array();
        endforeach;
    

    If you need to flatten the array afterwards you can for example use this:

    $recipients = array_merge(...$school_students)