I have an array with some of same ID value as shown in below.
[
{\"ID\":\"126871\",\"total\":\"200.00\",\"currency\":\"USD\",\"name\":\"John
What: Create an array that is grouped by 'ID' and 'Currency'. Accumulate currency for duplicates.
How:
Demonstration at eval.in
Code:
/** ----------------------------------------------
* Create an output array one row at a time.
*
* Group by Id and currency.
*
* @param array $groups
*
* @return array
*/
function getCurrencyGroups(array $groups)
{
$currencyGroups = array();
foreach ($groups as $item) {
$id = $item['ID'];
$currency = $item['currency'];
$amount = $item['total'];
if (!isset($currencyGroups[$id][$currency])) {
$currencyGroups[$id][$currency] = $amount;
}
else {
$currencyGroups[$id][$currency] += $amount;
}
}
return $currencyGroups;
}
Run it:
$currencyGroups = getCurrencyGroups($source);
Output:
array (size=2)
126871 =>
array (size=1)
'USD' => string '200.00' (length=6)
126872 =>
array (size=2)
'Euro' => float 4000
'USD' => string '500.00' (length=6)