在 foreach 中处理 codeigniter php array_merge 的最佳方法是什么?

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

我正在尝试列出 school_location_id = 1 学校的所有学生,我使用 codeigniter 的 USE 连接到多个学校数据库。我的挑战是它只列出了最后一所学校的学生。 下面是我的代码,

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

$school_students 被你的每一次 foreach-loop 覆盖。一种替代方法是简单地将结果添加到数组中,如下所示:

    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;

如果你之后需要展平数组,你可以使用这个:

$recipients = array_merge(...$school_students)