Search for duplicates, if found sum values - php

I have this array :
$data = [
0 => [
'date' => '2018-09-12',
'department' => 12,
'country' => 14,
'total' => 12
],
1 => [
'date' => '2018-09-12',
'department' => 12,
'country' => 14,
'total' => 18
],
2 => [
'date' => '2018-09-12',
'department' => 12,
'country' => 15,
'total' => 10
]
];
The return should be :
$return = [
0 => [
'date' => '2018-09-12',
'department' => 12,
'country' => 14,
'total' => 30
],
1 => [
'date' => '2018-09-12',
'department' => 12,
'country' => 15,
'total' => 10
]
];
I tried like this :
foreach ($data as $value) {
if(!in_array($value, $data)) {
$result[] = $data;
}
}
The idea is, if all fields except total are indentical, then add total to the existing total with the same fields. Please help me. Thx in advance and sorry for my english

You can do this by looping through your array, comparing all the other values of each element (date, department and country) with previously seen values and summing the totals when you get a match. This code uses serialize to generate a composite key of the other values for comparison:
$output = array();
$keys = array();
foreach ($data as $value) {
$total = $value['total'];
unset($value['total']);
$key = serialize($value);
if (($k = array_search($key, $keys)) !== false) {
$output[$k]['total'] += $total;
}
else {
$keys[] = $key;
$output[] = array_merge($value, array('total' => $total));
}
}
print_r($output);
Output:
Array (
[0] => Array (
[date] => 2018-09-12
[department] => 12
[country] => 14
[total] => 30
)
[1] => Array (
[date] => 2018-09-12
[department] => 12
[country] => 15
[total] => 10
)
)
Demo on 3v4l.org
By using the composite key as the index into the $output array, we can simplify this code, we just need to use array_values after the loop to re-index the $output array:
$output = array();
foreach ($data as $value) {
$v = $value;
unset($v['total']);
$key = serialize($v);
if (isset($output[$key])) {
$output[$key]['total'] += $value['total'];
}
else {
$output[$key] = $value;
}
}
$output = array_values($output);
print_r($output);
Output is the same as before. Demo on 3v4l.org

You can also try this method as it doesn't involve much memory intensive operations such as merging, especially while working with large amount of data:
$new_data=[];
foreach($data as $key=>$value){
$i=array_search($value["date"],array_column($new_data,"date"));
if(($i!==false)&&($new_data[$i]["department"]==$value["department"])&&($new_data[$i]["country"]==$value["country"])){
$new_data[$i]["total"]+=$value["total"];
}
else{
$new_data[]=$value;
}
}
print_r($new_data);

Related

PHP: substract values of 2 arrays of different length

Well, I've got two following arrays:
$incomesArr = [
['1605564000' => 121],
['1605736800' => 3.50],
];
$expensesArr = [
['1605736800' => 3.50],
['1605736800' => 3.50],
['1605564000' => 28],
['1605936000' => 50]
];
As you can see from the variable names, these are the expenses and incomes for the current date (it is a timestamp). All I want to do is to generate the "Revenue" data by substracting value of $expensesArr from $incomesArr with corresponding date, and if there is no date, then substract from 0. Also, if there is no corresponding date in the $expensesArr, then substract nothing (or 0).
Basically, I want to achieve the following result:
['1605564000', 93]; // 121 - 28 = 93
['1605736800', -3.50] // 3.50 - 3.50 - 3.50 (since both expenses are for the same date)
['1605936000', -50] // 0 - 50, since there is no income for that day.
Please note, that the output result should be in the ['key', 'value'] format, not the ['key' => 'value'], since I send these data to jQuery Flot (displaying graphs).
I carry about the performance, since there may be kind of significant amount of data and the best way for me to achieve this is without foreach loop, however if it is the only possible option, then foreach it is!
Any help is highly appreciated. Thank you in advance!
P.S. If it would help, then I do this in Laravel, however I don't think that there is a special helper exactly for that, since I already examined the Laravel documentation multiple times :)
My previous attempt was a bit confusing and scary, but here it is:
$newArr = array_merge([$incomesArr, $expensesArr]);
foreach ($incomesArr as $k => $v){
$sub = $v - $expensesArr[$k];
// this is like : array1[1]-array2[1]
}
$finalArr = [];
foreach($newArr as $key => $value) {
var_dump($value);
foreach ($value as $key => $val) {
$finalArr[$key] = ($val[$key] ?? 0) - ($val[$key] ?? 0);
}
}
$incomesArr = [
['1605564000' => 121],
['1605736800' => 3.50],
];
$expensesArr = [
['1605736800' => 3.50],
['1605736800' => 3.50],
['1605564000' => 28],
['1605936000' => 50]
];
// get data
$dataArr = [];
foreach([-1 => $expensesArr, 1 => $incomesArr] as $ratio => $list){
foreach($list as $value){
$time = key($value);
$dataArr[$time] = ($dataArr[$time] ?? 0) + ($value[$time] * $ratio);
}
}
// convert to your format
$finalArr = [];
foreach($dataArr as $time => $value){
$finalArr []= [$time, $value];
}
print_r($finalArr);
Output
Array
(
[0] => Array
(
[0] => 1605736800
[1] => -3.5
)
[1] => Array
(
[0] => 1605564000
[1] => 93
)
[2] => Array
(
[0] => 1605936000
[1] => -50
)
)
I would split it into two functions like so:
$incomesArr = [
['1605564000' => 121],
['1605736800' => 3.50],
];
$expensesArr = [
['1605736800' => 3.50],
['1605736800' => 3.50],
['1605564000' => 28],
['1605936000' => 50]
];
function getTotalByKey($inputArray, $inputKey)
{
$sum = 0;
foreach ($inputArray as $subArray)
foreach ($subArray as $key => $value) {
$sum += $key === $inputKey ? $value : 0;
}
return $sum;
}
function getProfitByKey($incomesArray, $expensesArray, $key){
return getTotalByKey($incomesArray, $key) - getTotalByKey($expensesArray, $key);
}
$profit = getProfitByKey($incomesArr, $expensesArr, 1605736800); // Outputs -3.5
$incomesArr = [
['1605564000' => 121],
['1605736800' => 3.50],
];
$expensesArr = [
['1605736800' => 3.50],
['1605736800' => 3.50],
['1605564000' => 28],
['1605936000' => 50]
];
$tmp = [];
$final = [];
foreach ($incomesArr as $pair)
{
foreach ($pair as $date => $amount)
{
$tmp[$date] = ($tmp[$date] ?? 0) + $amount;
}
}
foreach ($expensesArr as $pair)
{
foreach ($pair as $date => $amount)
{
$tmp[$date] = ($tmp[$date] ?? 0) - $amount;
}
}
print_r($tmp);
foreach ($tmp as $date => $amount)
{
$final[] = [$date, $amount];
}
print_r($final);
Output
Array
(
[1605564000] => 93
[1605736800] => -3.5
[1605936000] => -50
)
Array
(
[0] => Array
(
[0] => 1605564000
[1] => 93
)
[1] => Array
(
[0] => 1605736800
[1] => -3.5
)
[2] => Array
(
[0] => 1605936000
[1] => -50
)
)

PHP remove duplicates and sum of them from array based on 2 keys [duplicate]

I have this array :
$data = [
0 => [
'date' => '2018-09-12',
'department' => 12,
'country' => 14,
'total' => 12
],
1 => [
'date' => '2018-09-12',
'department' => 12,
'country' => 14,
'total' => 18
],
2 => [
'date' => '2018-09-12',
'department' => 12,
'country' => 15,
'total' => 10
]
];
The return should be :
$return = [
0 => [
'date' => '2018-09-12',
'department' => 12,
'country' => 14,
'total' => 30
],
1 => [
'date' => '2018-09-12',
'department' => 12,
'country' => 15,
'total' => 10
]
];
I tried like this :
foreach ($data as $value) {
if(!in_array($value, $data)) {
$result[] = $data;
}
}
The idea is, if all fields except total are indentical, then add total to the existing total with the same fields. Please help me. Thx in advance and sorry for my english
You can do this by looping through your array, comparing all the other values of each element (date, department and country) with previously seen values and summing the totals when you get a match. This code uses serialize to generate a composite key of the other values for comparison:
$output = array();
$keys = array();
foreach ($data as $value) {
$total = $value['total'];
unset($value['total']);
$key = serialize($value);
if (($k = array_search($key, $keys)) !== false) {
$output[$k]['total'] += $total;
}
else {
$keys[] = $key;
$output[] = array_merge($value, array('total' => $total));
}
}
print_r($output);
Output:
Array (
[0] => Array (
[date] => 2018-09-12
[department] => 12
[country] => 14
[total] => 30
)
[1] => Array (
[date] => 2018-09-12
[department] => 12
[country] => 15
[total] => 10
)
)
Demo on 3v4l.org
By using the composite key as the index into the $output array, we can simplify this code, we just need to use array_values after the loop to re-index the $output array:
$output = array();
foreach ($data as $value) {
$v = $value;
unset($v['total']);
$key = serialize($v);
if (isset($output[$key])) {
$output[$key]['total'] += $value['total'];
}
else {
$output[$key] = $value;
}
}
$output = array_values($output);
print_r($output);
Output is the same as before. Demo on 3v4l.org
You can also try this method as it doesn't involve much memory intensive operations such as merging, especially while working with large amount of data:
$new_data=[];
foreach($data as $key=>$value){
$i=array_search($value["date"],array_column($new_data,"date"));
if(($i!==false)&&($new_data[$i]["department"]==$value["department"])&&($new_data[$i]["country"]==$value["country"])){
$new_data[$i]["total"]+=$value["total"];
}
else{
$new_data[]=$value;
}
}
print_r($new_data);

Multi dimensional array, sum values of the same key

I have a multi dimensional array. I need to sum up the distance values with same 'driver' and 'date' keys
Input :
$firstArr = array(
0 =>array('driver'=>'xxxx',
'distance' => 100,
'vehicle' => 1,
'date' => '2019-10'),
1=>array('driver'=>'xxxx',
'distance' => 200,
'vehicle' => 2,
'date' => '2019-10'),
2=>array('driver'=>'yyyy',
'distance' => 100,
'vehicle' => 3,
'date' => '2019-10'));
Output Expected :
$finalArr = array(
0 =>array('driver'=>'xxxx',
'distance' => 300,
'vehicle' => '1,2',
'date' => '2019-10'),
1=>array('driver'=>'yyyy',
'distance' => 100,
'vehicle' => 3,
'date' => '2019-10'));
I tried below code. But the output is a datewise array.
$subArr = array();
foreach($firstArr as $key => $val){
$subArr[$val['driver']][$val['date']]['distance'] += $val['distance'];
$subArr[$val['driver']][$val['date']]['vehicle'] .= $val['vehicle'].',';
$subArr[$val['driver']][$val['date']]['date'] = $val['date'];
$subArr[$val['driver']][$val['date']]['driver'] = $val['driver'];
}
$result = array_values($subArr);
You can use the dirver and date as a key, Demo
$result = [];
foreach($array as $v){
$key = $v["driver"] . "_" . $v["date"];
if(isset($result[$key])){
$result[$key]["distance"] += $v["distance"];
}else{
$result[$key] = $v;
}
}
$result = array_values($result);
You can also use array_reduce to sum up the distance and the vehicles by driver and date.
With the help of array_combine we can set the initial array if not exists for each driver date combo and then do the processing of the required fields.
$keys = array_keys($input[0]);
$result = array_reduce($input, function ($sum, $row) use ($keys) {
$key = $row['driver'] . $row['date'];
$sum[$key] = $sum[$key] ?? array_combine($keys, [$row['driver'], null, null, $row['date']]);
$sum[$key]['distance'] += $row['distance'];
$sum[$key]['vehicle'] .= (($sum[$key]['vehicle']) ? ',': '' ) . $row['vehicle'];
return $sum;
}, []);
Results in:
Array
(
[xxxx2019-10] => Array
(
[driver] => xxxx
[distance] => 300
[vehicle] => 1,2
[date] => 2019-10
)
[yyyy2019-10] => Array
(
[driver] => yyyy
[distance] => 100
[vehicle] => 3
[date] => 2019-10
)
)

How to subtract all column values in multi-dimensional array in Php?

How can I subtract all the columns values? My array is like
Array
(
[0] => Array
(
[id] => 1
[web_traffic] => 442
[form_users] => 131
[date] => 20181004
)
[1] => Array
(
[id] => 2
[web_traffic] => 102
[form_users] => 15
[date] => 20181003
)
[2] => Array
(
[id] => 3
[web_traffic] => 387
[form_users] => 97
[date] => 20181002
)
)
I need to subtract the each column(except date & id) and get the result based on date(Ascending order). For example 20181004 means 4th October 2018. My output should like the below
Array
(
[web_traffic] => -152
[form_users] => -49
)
My code took reference from How to sum all column values in multi-dimensional array?
foreach ($data as $value) {
unset($value[ 'id' ]);
$time = date('Ymd', strtotime($value[ 'date' ]));
if (in_array($time, $dates)) {
$value[ 'date' ] = $time;
foreach ($value as $key => $secondValue) {
if ( !isset($output[ $key ])) {
$output[ $key ] = 0;
}
$output[ $key ] -= $secondValue;
}
}
}
Use PHP array_reduce() and array_column() like this:
$initial_array = array(array('id' => 1,
'web_traffic' => 442,
'form_users' => 131,
'date' => 20181004),
array('id' => 2,
'web_traffic' => 102,
'form_users' => 15,
'date' => 20181003),
array('id' => 3,
'web_traffic' => 387,
'form_users' => 97,
'date' => 20181002));
function sum($carry, $item)
{
$carry -= $item;
return $carry;
}
$web_traffic = array_column($initial_array, "web_traffic");
$form_users = array_column($initial_array, "form_users");
$date = array_column($initial_array, "date");
array_multisort($date, SORT_ASC, $form_users, SORT_DESC, $initial_array);
$result_array = Array(
"web_traffic" => array_reduce(array_column($initial_array, "web_traffic"), "sum",2*$initial_array[0]['web_traffic']),
"form_users" => array_reduce(array_column($initial_array, "form_users"), "sum",2*$initial_array[0]['form_users'])
);
print_r($result_array);
I would first sort the array using usort() in example.
Sorting first, because that can be tricky to substract in 1 loop the oldest datas to the newers one.
Separating intentions provide a cleaner code, easier to maintain.
The dates don't need to be converted into a date. The string is well formatted and can be used as is in a comparison and a sort. "20170101" < "20180101", "20180101" < "20181001" and "20181002" < "20181004"
When done, I'll save the first values as initial values to be used in substract.
Then, loop the sorted array and substract the 'web_traffic' and 'form_users' to the initial values.
$datas = array(array('id' => 1,
'web_traffic' => 442,
'form_users' => 131,
'date' => 20181004),
array('id' => 2,
'web_traffic' => 102,
'form_users' => 15,
'date' => 20181003),
array('id' => 3,
'web_traffic' => 387,
'form_users' => 97,
'date' => 20181002));
//If needed, you can backup the original array, because usort() will modify it.
$backUpDatas = $datas;
//Sort
usort($datas, function ($arr1, $arr2)
{
if (isset($arr1['date']) && isset($arr2['date']))
{
if ($arr1['date'] == $arr2['date'])
return (0);
return (($arr1['id'] > $arr2['id']) ? (-1) : (1));
}
});
//Initial values
$finalValues['web_traffic'] = $datas[0]['web_traffic'];
$finalValues['form_users'] = $datas[0]['form_users'];
//Substract
foreach ($datas as $key => $value)
{
if ($key > 0)
{
if (isset($value['web_traffic']))
$finalValues['web_traffic'] -= $value['web_traffic'];
if (isset($value['form_users']))
$finalValues['form_users'] -= $value['form_users'];
}
}
var_dump($finalValues);
Output :
array (size=2)
'web_traffic' => int -157
'form_users' => int -49

how to create unique array from array

Array
[0] => Array
(
[a1] => 12
[v1] => 3100.00
[v2] => 186.00
[v3] => 186.00
)
[1] => Array
(
[a1] => 12
[v1] => 1200.00
[v2] => 72.00
[v3] => 72.00
)
i want to create new array from this array
which is look like this as given below it should give me '12' common and add other values
Array
[0] => Array
(
[a1] => 12
[v1] => 4300.00
[v2] => 258.00
[v3] => 258.00
)
Try This code ,
foreach($value as $i=>$v) {
$temp[0]['a1'] = $v['a1'];
$temp[0]['v1'] += $v['v1'];
$temp[0]['v2'] += $v['v2'];
$temp[0]['v3'] += $v['v3'];
}
Please find below code:
<?php
$merged = array();
$res = array('a1'=>12,'v1'=>3100.00,'v2'=>186.00,'v3'=>186.00);
$res1 = array('a1'=>12,'v1'=>1200.00,'v2'=>72.00,'v3'=>72.00);
foreach ([$res, $res1] as $a) { // iterate both arrays
foreach ($a as $key => $value) { // iterate all keys+values
$merged[$key] = $value + (isset($merged[$key]) ? $merged[$key] : 0); // merge and add
}
}
print "<pre>";
print_r($merged);
die;
?>
It's a bit unclear the real your needs, so this solution only one of a few possible solutions.
This script a1 element is using as key, so it will work with more than one a1 value.
Example:
<?php
$a = [
[
'a1' => 12,
'v1' => 3100.00,
'v2' => 186.00,
'v3' => 186.00,
],
[
'a1' => 12,
'v1' => 1200.00,
'v2' => 72.00,
'v3' => 72.00,
],
[
'a1' => 13,
'v1' => 2100.00,
'v2' => 386.00,
'v3' => 386.00,
],
[
'a1' => 13,
'v1' => 1200.00,
'v2' => 72.00,
'v3' => 72.00,
]
];
$r = [];
foreach ($a as $item) {
$key = $item['a1'];
if (empty($r[$key]))
$r[$key] = $item;
else {
foreach ($item as $k => $v) {
if ($k !== 'a1')
$r[$key][$k] = empty($r[$key][$k]) ? $item[$k] : $r[$key][$k] + $item[$k];
}
}
}
print_r(array_values($r));
A simple foreach loop can do it.
$result = array();
foreach($yourArray as $arr){
foreach($arr as $i=>$v) {
if(!isset($result[$i])) {
$result[$i] = 0;
}
if($i == 'a1'){
$result[$i] = $v;
} else {
$result[$i] += $v;
}
}
}

Categories