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;
}
}
}
Related
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
)
)
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);
I am trying to create one array out of the two. Two arrays may be different lengths therefore the combine result should accommodate that and fill gaps with null.
My understanding is to first find a bigger array and loop over that, fill the gaps in the smaller array, and once that is done, merge it.
This is what I have done so far, but it feels very clunky, to the point I am starting to think - there must be a better way - less loops and maybe use some of the php array helpers methods ?
<?php
$result_keys = [];
$result_data = [];
$bigger = null;
$smaller = null;
$array1 = [
[
'dog' => 2,
'cat' => 3,
],
[
'dog' => 4,
'cat' => 2,
],
[
'dog' => 2,
'cat' => 3
]
];
$array2 = [
[
'bird' => 7,
],
[
'bird' => 5
]
];
// find which array is bigger
if (count($array1) >= count($array2)) {
$bigger = $array1;
$smaller = $array2;
} else {
$bigger = $array2;
$smaller = $array1;
};
// loop over bigger array
foreach ($bigger as $i => $record) {
foreach ($record as $key => $value) {
if ($i === 0) {
$result_keys[] = $key;
};
$result_data[$i][] = $value;
}
// fill gaps in smaller array
if (!isset($smaller[$i])) {
foreach ($smaller[$i-1] as $key => $value) {
$smaller[$i][$key] = null;
}
}
};
// loop over smaller array
foreach ($smaller as $i => $record) {
foreach ($record as $key => $value) {
if ($i === 0) {
$result_keys[] = $key;
};
$result_data[$i][] = $value;
}
};
var_dump($result_keys);
var_dump($result_data);
// // expected result
// $result_keys = ['dog', 'cat', 'bird'];
// $result_data = [
// [2,3,7],
// [4,2,5],
// [2,3,null]
// ];
My solution to your problem:
$array1 = [
[
'dog' => 2,
'cat' => 3,
],
[
'dog' => 4,
'cat' => 2,
],
[
'dog' => 2,
'cat' => 3
]
];
$array2 = [
[
'bird' => 7,
],
[
'bird' => 5
]
];
// get the number of values of the biggest array
$count = $count = count($array1) >= count($array2) ? count($array1) : count($array2);
$values = [];
$keys = [];
for ($i = 0; $i < $count; $i++) {
$a1 = $array1[$i] ?? [];
$a2 = $array2[$i] ?? [];
$keys = array_unique(array_merge($keys, array_keys($a1), array_keys($a2)));
$values[] = array_values(array_merge(array_fill_keys($keys, null), $a1, $a2));
}
print_r($keys);
print_r($values);
Results (test here):
Array
(
[0] => dog
[1] => cat
[2] => bird
)
Array
(
[0] => Array
(
[0] => 2
[1] => 3
[2] => 7
)
[1] => Array
(
[0] => 4
[1] => 2
[2] => 5
)
[2] => Array
(
[0] => 2
[1] => 3
[2] =>
)
)
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);
How can we find the count of duplicate elements in a multidimensional array,
I have an array like this:
Array
(
[0] => Array
(
[brti] => 29
)
[1] => Array
(
[voda] => 6
)
[2] => Array
(
[btel] => 8
)
[3] => Array
(
[btel] => 10
)
)
Question: How to simplify the structure of array, i mean can be counting the value if there is indicate that have same key ?
just like this:
Array
(
[0] => Array
(
[brti] => 29
)
[1] => Array
(
[voda] => 6
)
[2] => Array
(
[btel] => 18
)
)
So far, i've tried this way, but it didn't help me. My array is store in $test
$test = [sample array]
$count = array();
foreach ($test as $key => $value) {
foreach ($value as $k => $val) {
if (isset($count[$val])) {
++$count[$val];
} else {
$count[$value] = 1;
}
}
}
print_r($count);
<?php
$array = [
"0" => ["brti" => 29],
"1" => ["voda" => 6],
"2" => ["btel" => 8],
"3" => ["btel" => 10],
];
$final = array();
array_walk_recursive($array, function($item, $key) use (&$final){
$final[$key] = isset($final[$key]) ? $item + $final[$key] : $item;
});
print_r($final);
});
check demo
You can do it in very simple way,
$test = [];
foreach ($array as $value)
{
foreach ($value as $k => $v)
{
// $test[$k] = ($test[$k] ?? 0); // initialised if not php 7+
$test[$k] = (empty($test[$k]) ? 0: $test[$k]); // below php 7
$test[$k] += $v;
}
}
print_r($test);
Output:
Array
(
[brti] => 29
[voda] => 6
[btel] => 18
)
Working demo.