- Group the data by assigning temporary associative keys (mail values) to a new result array.
- While iterating, determine if you are processing the first occurrence of a mail value or not by calling
isset()
on the mail key of the result array.
- If this is the first instance of the mail, set all of the values in the subarray.
- If this is not the first instance of the mail value, adjust the pre-existing subarray.
- After looping, use
printf()
to concisely format your data as desired.
In case the float output syntax is unfamiliar, read this.
Code: (Demo)
$array = [
['mail' => 'mail1@example.com', 'coins' => '25000.00'],
['mail' => 'mail2@example.com', 'coins' => '500000.00'],
['mail' => 'mail1@example.com', 'coins' => '10000.00'],
['mail' => 'mail2@example.com', 'coins' => '10000.00'],
['mail' => 'mail3@example.com', '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 (...)
}
Output:
mail1@example.com (2), 35000.00 coins
mail2@example.com (2), 510000.00 coins
mail3@example.com (1), 20000.00 coins