我在Mysql连接时遇到了问题。我有两张桌子,一张center_contacts
桌和一张center_contacts_notes
. center_contacts_notes
通过两个表中的contact_id
进行链接。
center_contacts_notes
内部,每个contact_id
可以有多行,我想抓住所有这些并将它们放在结果的子数组中。
例如,这是我的center_contacts_notes
表的样子:
contact_id | note
------------------------
1 test
2 hello
3 sup
1 moo
这是我尝试获取数据的地方:
$this->db->select('center_contacts.id, FirstName, LastName, center_contacts_notes.note');
$this->db->from('center_contacts');
$this->db->join('center_contacts_notes', 'center_contacts_notes.contact_id = center_contacts.id');
请注意,我使用的是代码点火器 3。
这是我从中得到的:
Array
(
[id] => 1
[FirstName] => Bob
[LastName] => Smith
[note] => test
)
Array
(
[id] => 1
[FirstName] => Bob
[LastName] => Smith
[note] => moo
)
这是我的结果中的两个不同的数组。这对我的使用来说是不切实际的,因为我需要一个包含两个音符的数组。像这样:
Array
(
[id] => 1
[FirstName] => Bob
[LastName] => Smith
[note] => Array(test, moo)
)
这是否可能,如果是,我将如何实现它?谢谢。
您是否可以像您提到的那样获得二维数组,但是有一种解决方法可以获得类似的结果。这可能对您有所帮助。
您需要做的是使用 Group By
和 group_concat()
. 通过contact_id
Group by
表,并在center_contacts_notes.note
上应用group_concat()
。
您的查询应如下所示。
$this->db->select('center_contacts.id, FirstName, LastName, GROUP_CONCAT(center_contacts_notes.note)');
$this->db->from('center_contacts');
$this->db->join('center_contacts_notes', 'center_contacts_notes.contact_id = center_contacts.id');
$this->db->group_by('center_contacts.id');
默认情况下,group_concat 将按 ,
连接列。您可以通过以下方式更改它。
GROUP_CONCAT(center_contacts_notes.note SEPARATOR 'YOUR_SEPARATOR_STRING')
这将返回如下结果:
Array
(
[id] => 1
[FirstName] => Bob
[LastName] => Smith
[note] => test[YOUR_SEPARATOR_STRING] moo
)
您可以使用 PHP explode 通过提供分隔符值将注释字符串转换为数组。