按一列值对行进行分组,对另一列求和并计算出现次数

问题描述 投票:0回答:2

我已经构建了相当复杂的数组,其中包含其他带有用户邮件和“硬币”值的数组。我需要删除和计算重复的邮件并合并“硬币”值。

Array (
    [0] => Array ( [mail] => [email protected] [coins] => 25000.00 ) 
    [1] => Array ( [mail] => [email protected] [coins] => 500000.00 ) 
    [2] => Array ( [mail] => [email protected] [coins] => 10000.00 ) 
    [3] => Array ( [mail] => [email protected] [coins] => 10000.00 )
    [4] => Array ( [mail] => [email protected] [coins] => 20000.00 )
) 

所以输出看起来像:

[email protected] (2), 35000.00 coins
[email protected] (2), 510000.00 coins
[email protected] (1), 20000.00 coins

非常感谢!

php arrays merge duplicates
2个回答
1
投票
$grouped = [];
foreach ($array as $item) {
    $email = $item['mail'];
    if (empty($grouped[$email])) {
        $grouped[$email] = ['count' => 0, 'sum' => 0];
    }

    $grouped[$email]['count']++;
    $grouped[$email]['sum'] += $item['coins'];
}

foreach ($grouped as $email => $data) {
    echo $email . '(' . $data['count'] . ') ' . $data['sum'] . ' coins';
}

0
投票
  1. 通过将临时关联键(邮件值)分配给新的结果数组来对数据进行分组。
  2. 迭代时,通过在结果数组的邮件键上调用
    isset()
    来确定是否正在处理邮件值的第一次出现。
  3. 如果这是邮件的第一个实例,请设置子数组中的所有值。
  4. 如果这不是邮件值的第一个实例,请调整预先存在的子数组。
  5. 循环后,使用
    printf()
    根据需要简洁地格式化数据。

如果浮点输出语法不熟悉,请阅读this

代码:(演示

$array = [
    ['mail' => '[email protected]', 'coins' => '25000.00'],
    ['mail' => '[email protected]', 'coins' => '500000.00'],
    ['mail' => '[email protected]', 'coins' => '10000.00'],
    ['mail' => '[email protected]', 'coins' => '10000.00'],
    ['mail' => '[email protected]', 'coins' => '20000.00'],
];

$result = [];
foreach ($array as ['mail' => $mail, 'coins' => $coins]) {
    if (!isset($result[$mail])) {
        $result[$mail] = [1, $coins];  // declare the data for the first instance of mail
    } else {
        ++$result[$mail][0];          // increment the running count
        $result[$mail][1] += $coins;  // add coins to running total
    }
}

foreach ($result as $mail => $row) {
    printf("%s (%d), %.2f coins\n", $mail, ...$row);  // unpack the row with the splat operator (...)
}

输出:

[email protected] (2), 35000.00 coins
[email protected] (2), 510000.00 coins
[email protected] (1), 20000.00 coins
© www.soinside.com 2019 - 2024. All rights reserved.