0

I have the following query

$sql = 'SELECT F.ID, F.name as famName,F.contactEmail,F.address,F.phone,F.sitting, M.date,M.time,M.meeting, P.name as partName,P.email, R.numAttendees,R.deltoken FROM Registration R, meeting M, Participants P,Family F WHERE date = CURDATE() + INTERVAL 1 DAY AND R.participant = P.ID AND R.meeting= M.ID AND M.family = F.ID ORDER BY M.meeting'; $data = $pdo -> query($sql)->fetchAll(PDO::FETCH_GROUP); 

which returns exactly what I need. However, I then need to use the same information grouped by email. Is there any way to do that, without requerying the database?

3
  • 1
    You can sort any arrray however you want it. There are many sort algorythms out there, for example quicksort. Commented Jan 26, 2017 at 11:23
  • Do you know about php arrays? php.net/manual/en/language.types.array.php Are you aware that the index (the key) of an array can be a text string? You may want to consider writing code that will extract your $data array of arrays into one indexed by your contact email. Commented Jan 26, 2017 at 11:57
  • @O.Jones, the problem is that I need the data grouped in two different ways in the same script - first by F.ID, then by P.email. I want to know if there is a way to "refetch" the data without requerying the database Commented Jan 26, 2017 at 16:26

1 Answer 1

3
$grouped_by_email = array(); foreach($data as $row) { if(!isset($grouped_by_email[$row['email']])) { $grouped_by_email[$row['email']] = array(); } $grouped_by_email[$row['email']][] = $row; } 

This will create an array of arrays with the email as the key.

If you want to do this similar to the way "GROUP BY" works in SQL, then use this:

$grouped_by_email = array(); foreach ($data as $row) { if (!isset($grouped_by_email[$row['email']])) { $grouped_by_email[$row['email']] = $row; } else { $grouped_by_email[$row['email']] = aggregate($grouped_by_email[$row['email']], $row); } } function aggregate($existingValue, $newValue) { // Here write the olumn you want to combine and how. $newValue['numAttendees'] += $existingValue['numAttendees']; return $newValue; } 
Sign up to request clarification or add additional context in comments.

2 Comments

PHP does not get table aliases from MySQL so it should be $row['contactEmail']
this doesn't produce anything close to what I'm looking for (and I want it grouped by email, not contactEmail)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.