I have been trying all day to sum below array, based on the value and only get the distinct values.
Here is my input array:
[
{
"commoditycodes": "6204.4400",
"statisticalvalue": 1152.6,
"cvr": "DK35425950"
},
{
"commoditycodes": "6204.4400",
"statisticalvalue": 542.4,
"cvr": "DK35425950"
},
{
"commoditycodes": "6104.4300",
"statisticalvalue": 1827,
"cvr": "DK35425950"
},
{
"commoditycodes": "6114.3000",
"statisticalvalue": 5211.36,
"cvr": "DK37968552"
},
{
"commoditycodes": "6114.3000",
"statisticalvalue": 798.64,
"cvr": "DK99999999"
}
]
I am trying to "gather" all arrays that have the same cvr
value, but still show it distinct based on commoditycodes
. Like this:
{
"commoditycodes": "6204.4400",
"statisticalvalue": 1695,
"cvr": "DK35425950"
},
{
"commoditycodes": "6104.4300",
"statisticalvalue": 1827,
"cvr": "DK35425950"
},
{
"commoditycodes": "6114.3000",
"statisticalvalue": 5211.36,
"cvr": "DK37968552"
},
{
"commoditycodes": "6114.3000",
"statisticalvalue": 798.64,
"cvr": "DK99999999"
}
]
As you can see, from the input, the first two results from my array have:
We then sum the statisticalvalue
.
The third result have the same CVR value as the two first, however the commoditycode
value is different - so this is an unique value.
The fourth and fifth elements of my arrays is both unique as well.
So basically, I am trying to sum statisticalvalue
where:
I have tried below:
$result = [];
foreach ($array as $val) {
//Not a duplicate cvr code
if (!isset($result[$val['cvr']])) {
$result[$val['cvr']] = $val;
//Duplicate cvr code.
} else {
$result[$val['cvr']]['statisticalvalue'] += $val['statisticalvalue'];
}
}
But that returns below, which only take the unique cvr
values - but not the commoditycodes
:
[
{
"commoditycodes": "6104.6300",
"statisticalvalue": 68701.56,
"cvr": "DK35425950"
},
{
"commoditycodes": "6104.6300",
"statisticalvalue": 21108.95,
"cvr": "DK37968552"
},
{
"commoditycodes": "6114.3000",
"statisticalvalue": 798.64,
"cvr": "DK99999999"
}
]
I am totally lost on how to check for this?
Make an array with a complex index $val['cvr'].'|'.$val['commoditycodes']
$result = [];
foreach ($array as $val) {
$index = $val['cvr'].'|'.$val['commoditycodes'];
if (!isset($result[$index])) {
$result[$index] = $val;
//Duplicate
} else {
$result[$index]['statisticalvalue'] += $val['statisticalvalue'];
}
}
If you want to make result array with numeric index, add after loop:
$result = array_values($result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With