Your task desires a single string containing comma-separated email addresses -- SQL can do all of that for you plus a few convenient flourishes.
$db = JFactory::getDBO();
try {
$query = $db->getQuery(true)
->select("GROUP_CONCAT(DISTINCT B.email ORDER BY B.email)")
->from("lc_community_groups_members A")
->innerJoin("lc_users B ON A.memberid = B.id")
->where("A.groupid = 1 AND A.approved = 1");
//echo $query->dump();
$db->setQuery($query);
if (!$emails = $db->loadResult()) {
echo "No Qualifying Email Addresses";
} else {
echo $emails;
}
} catch (Exception $e) {
echo "Syntax Error"; // . $e->getMessage();
}
With sample data like this:
| lc_community_groups_members | JOIN ON memberid=id | lc_users |
|-------------------------------------| |-------------------------|
| memberid | groupid | approved | | id | email |
|------------|-----------|------------| |-------------------------|
| 1 | 2 | 1 | < | 1 | [email protected] |
| 2 | 1 | 1 | < | 2 | [email protected] |
| 3 | 1 | 0 | < | 3 | [email protected] |
| 4 | 1 | 1 | < | 4 | [email protected] |
| 5 | 1 | 1 | < | 5 | [email protected] |
| 6 | 2 | 0 | < | 6 | [email protected] |
| 7 | 1 | 0 | < | 7 | [email protected] |
| 8 | 1 | 1 | < | 8 | [email protected] |
| 9 | 1 | 1 | < | 9 | [email protected] |
--------------------------------------- ---------------------------
You would be expecting the emails from ids: 2,4,5,8,9
- INNER JOIN is used because null rows are not desired.
- GROUP_CONCAT() is a perfect tool for gluing together the email values with commas. It also provides the added benefit of removing duplicates (for a streamlined mail-out) and alphabetizing (in case you are manually scanning the output).
- loadResult() is the method to call when your resultset is a single value.
The output from my code block is:
[email protected],[email protected],[email protected],[email protected]