我如何重组数组

时间:2017-01-26 11:20:46

标签: php mysql pdo

我有以下查询

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

完全返回我需要的内容。但是,我需要使用通过电子邮件分组的相同信息。 有没有办法做到这一点,没有重新查询数据库?

1 个答案:

答案 0 :(得分: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;
}

这将创建一个以电子邮件为密钥的数组数组。

如果你想这样做的方式" GROUP BY"在SQL中工作,然后使用:

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