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



我正在尝试列出学校_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循环的每次传递中都会被覆盖。一种选择是简单地将结果添加到数组中,如下所示:

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)

最新更新