I have two multi dimensional array.If the key is same then i want to get the sum how do i do that.
one is-
Array
(
[2018-08-02] => Array
(
[male] => 1
[female] => 0
)
[2018-08-07] => Array
(
[male] => 1
[female] => 0
)
[2018-08-09] => Array
(
[male] => 1
[female] => 5
)
)
2nd one is-
one is-
Array
(
[2018-08-02] => Array
(
[male] => 3
[female] => 4
)
[2018-08-07] => Array
(
[male] => 1
[female] => 5
)
[2018-08-06] => Array
(
[male] => 2
[female] => 3
)
)
so my result would be
Array
(
[2018-08-02] => Array
(
[male] => 4
[female] => 4
)
[2018-08-07] => Array
(
[male] => 2
[female] => 5
)
[2018-08-09] => Array
(
[male] => 1
[female] => 5
)
[2018-08-06] => Array
(
[male] => 2
[female] => 3
)
)
Code is
foreach ($reportlist as $reportlists){
$daterep=$reportlists['act_date'];
$arr[$daterep]['male']=$reportlists['male_cnt'];
$arr[$daterep]['female']=$reportlists['female_cnt'];
}
foreach ($ureportlist as $ureportlists){
$daterep=$rueportlists['act_date'];
$arr2[$daterep]['male']=$reportlists['male_cnt'];
$arr2[$daterep]['female']=$reportlists['female_cnt'];
}
Here is your code,
<?php
function pr($arr = [])
{
echo "<pre>";
print_r($arr);
echo "</pre>";
}
$arr1 = array
(
"2018-08-02" => array
(
"male" => 1,
"female" => 0,
),
"2018-08-07" => array
(
"male" => 1,
"female" => 0,
),
"2018-08-09" => array
(
"male" => 1,
"female" => 5,
),
);
$arr2 = array
(
"2018-08-02" => array
(
"male" => 3,
"female" => 4,
),
"2018-08-07" => array
(
"male" => 1,
"female" => 5,
),
"2018-08-06" => array
(
"male" => 2,
"female" => 3,
),
);
function custom_function($arr){
$retArr = array();
foreach ($arr as $child) { // arr1, arr2
foreach ($child as $key => $value) { // traversing through keys
foreach($value as $k => $v){
if (isset($retArr[$key][$k])) { // if key is set then add
$retArr[$key][$k] += $v;
} else {
$retArr[$key][$k] = $v; // else initiate
}
}
}
}
return $retArr;
}
$result=custom_function(array($arr1,$arr2));
pr($result);die;
Here is your working code
You can use array_intersect_key() to check if there is a matching results to add them.
for example, Let's assume your two arrays are $array1 and $array2. Then you can use
$result = array_intersect_key($array1, $array2);
This will return intersection in an array. So you can identify which keys have (in your case, which dates) need to be add.
You can use array_merge_recursive to join arrrays and then sum sub-arrays in the result array
$res = array_merge_recursive($arr1, $arr2);
foreach($res as &$date) {
foreach($date as &$sex) {
$sex = array_sum((array) $sex);
}
}
print_r($res);
demo
You simply need to iterate the 2nd array and determine whether or not the date keys exist in the 1st array. isset() is the best / most efficient way to run that check.
If a date from the 2nd array does not yet exist in the first, you can simply store the row's data to the 1st array. If the date already exists in the 1st array, then you will need to add (individually) the male and female values.
Code: (Demo)
$array1 = [
'2018-08-02' => ['male' => 1, 'female' => 0],
'2018-08-07' => ['male' => 1, 'female' => 0],
'2018-08-09' => ['male' => 1, 'female' => 5]
];
$array2 = [
'2018-08-02' => ['male' => 3, 'female' => 4],
'2018-08-07' => ['male' => 1, 'female' => 5],
'2018-08-06' => ['male' => 2, 'female' => 3]
];
foreach ($array2 as $date => $row) {
if (!isset($array1[$date])) {
$array1[$date] = $row; // store row data with unique date
} else {
$array1[$date]['male'] += $row['male']; // perform addition
$array1[$date]['female'] += $row['female']; // perform addition
}
}
// ksort($array1); if you want to order by date
var_export($array1);
Output:
array (
'2018-08-02' =>
array (
'male' => 4,
'female' => 4,
),
'2018-08-07' =>
array (
'male' => 2,
'female' => 5,
),
'2018-08-09' =>
array (
'male' => 1,
'female' => 5,
),
'2018-08-06' =>
array (
'male' => 2,
'female' => 3,
),
)
Related
I have an array with the following structure:
[0] => Array
(
[venue1] => 1
[venue2] => 2
)
[1] => Array
(
[venue1] => 3
[venue2] => 4
)
[2] => Array
(
[venue1] => 2
[venue2] => 1
)
[3] => Array
(
[venue1] => 5
[venue2] => 6
)
I need to remove the duplicate "pair of values", in this case row [0] and row [2]
I tried it with that code, but it doesn't work (and of course it's not very elegant) ;-)
foreach ( $compare_arr as $v1 )
{
$key = array_search( intval($v1[venue1]), array_column( $compare_arr, 'venue2' ) );
if ( $key <> '' ) unset($compare_arr[$key]);
}
Do you have an idea how to solve this?
Thanks a lot for your help!
Oliver
Here is an approach where an intermediate array is formed of sorted values. That you can then search for to find duplicate pairs to remove.
<?php
$venues =
array (
0 =>
array (
'venue1' => 1,
'venue2' => 2,
),
1 =>
array (
'venue1' => 3,
'venue2' => 4,
),
2 =>
array (
'venue1' => 2,
'venue2' => 1,
),
3 =>
array (
'venue1' => 5,
'venue2' => 6,
),
);
$result = $pairs = $venues;
array_walk($pairs, 'sort');
var_export($pairs);
foreach($pairs as $k => $pair) {
if(count(array_keys($pairs, $pair)) > 1) {
unset($result[$k]);
}
}
var_export($result);
Output:
array (
0 =>
array (
0 => 1,
1 => 2,
),
1 =>
array (
0 => 3,
1 => 4,
),
2 =>
array (
0 => 1,
1 => 2,
),
3 =>
array (
0 => 5,
1 => 6,
),
)array (
1 =>
array (
'venue1' => 3,
'venue2' => 4,
),
3 =>
array (
'venue1' => 5,
'venue2' => 6,
),
)
If you want to remove occurring duplicates rather than pruning out duplicates altogether, you can do an array_unique on the sorted array above and then use the remaining keys to filter the original array.
$tmp = $venues;
array_walk($tmp, 'sort');
$tmp = array_unique($tmp, SORT_REGULAR);
$result = array_intersect_key($venues, $tmp);
var_export($result);
Output:
array (
0 =>
array (
'venue1' => 1,
'venue2' => 2,
),
1 =>
array (
'venue1' => 3,
'venue2' => 4,
),
3 =>
array (
'venue1' => 5,
'venue2' => 6,
),
)
You might also first loop the array creating a compound key based on the ordered keys.
Then you can filter the result only keeping arrays where the count is 2 as nothing is added because there are no duplicates.
For example
$result = [];
$compare_arr = [
["venue1" => 1, "venue2" => 2],
["venue1" => 3, "venue2" => 4],
["venue1" => 2, "venue2" => 1],
["venue1" => 5, "venue2" => 6],
];
foreach ($compare_arr as $v1) {
sort($v1);
$cKey = $v1[0] .'-'. $v1[1];
if (array_key_exists($cKey, $result)) {
$result[$cKey][] = $v1;
continue;
}
$result[$cKey] = $v1;
}
$result = array_filter($result, function($item) {
return count($item) === 2;
});
print_r($result);
Output
Array
(
[3-4] => Array
(
[0] => 3
[1] => 4
)
[5-6] => Array
(
[0] => 5
[1] => 6
)
)
You can see the compound keys are the values with a - in between. If you want to have the keys numbered from 0, you can use array_values.
Php demo
Edit
If you want to keep the first matching single pair, you can check for the compound key and if it already exists continue the loop without overwriting the existing one.
$result = [];
$compare_arr = [
["venue1" => 1, "venue2" => 2],
["venue1" => 3, "venue2" => 4],
["venue1" => 2, "venue2" => 1],
["venue1" => 5, "venue2" => 6]
];
foreach ($compare_arr as $v1) {
sort($v1);
$cKey = $v1[0] .'-'. $v1[1];
if (array_key_exists($cKey, $result)) {
continue;
}
$result[$cKey] = $v1;
}
print_r($result);
Output
Array
(
[1-2] => Array
(
[0] => 1
[1] => 2
)
[3-4] => Array
(
[0] => 3
[1] => 4
)
[5-6] => Array
(
[0] => 5
[1] => 6
)
)
Php demo
Whether you use a classic foreach() loop or functional iteration, there is no reason to iterate the input array more than once.
This snippet will appear nearly identical to TheFourthBird's answer, but I don't like the unnecessary use of continue. This snippet will ensure no that rows in the result array have 100% shared venue values (in any order). The subarray keys will also not suffer reordering; in other words the first element key will be venue1 then the second element will be venue2. Using implode() offers additional flexibility because the code won't need to be altered if the number of elements in each row changes.
$result = [];
foreach ($data as $index => $row) {
sort($row);
$key = implode('-', $row);
if (!isset($result[$key])) {
$result[$key] = $data[$index];
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'venue1' => 1,
'venue2' => 2,
),
1 =>
array (
'venue1' => 3,
'venue2' => 4,
),
2 =>
array (
'venue1' => 5,
'venue2' => 6,
),
)
To completely remove all rows where venue values are shared, maintain a "found" array as well as a "result" array.
Code: (Demo)
$result = [];
foreach ($data as $index => $row) {
sort($row);
$key = implode('-', $row);
if (!isset($found[$key])) {
$found[$key] = true;
$result[$key] = $data[$index];
} else {
unset($result[$key]);
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'venue1' => 3,
'venue2' => 4,
),
1 =>
array (
'venue1' => 5,
'venue2' => 6,
),
)
I'm having this array:
array(
[1] => Array
(
[1111] => Array
(
[one] => 70
[two] => 7.0
)
)
[2] => Array
(
[1111] => Array
(
[one] => 10
[two] => 2.0
)
)
)
And i want it to sum [one] and [two] of the two different arrays and output an array like this:
Array
(
[1111] => Array (
[one] => 80
[two] => 9.0
)
)
Based on the key "1111"
I have tried with the following
$array = array_values( $array );
$sum_array = [];
foreach ( $array as $k => $sub_array ) {
foreach ( $sub_array as $id => $value ) {
$sum_array[$id] += array_key_exists( $id, $sum_array ) ? $sum_array[$id] += $value : $sum_array[$id] = $value;
$sum_array[$id]['two'] += array_sum( $sum_array[$id]['two'] ) / ( 100 * count( $sum_array[$id]['count'] ) );
}
}
But that gives me only the first value like this:
Array
(
[1111] => Array (
[one] => 70
[two] => 7.0
)
)
Can someone please tell me what i'm doing wrong?
You could use the array_reduce to reduce your array to only one element.
The array_reduce function takes two ( sometime three ) parameters. The first one is the array, the second one is a callback with two parameters , the collector, and the current item. If there is a third parameters to the array_reduce function, it will be used to initialize the collector ( like in our case ).
The function will parse each item and do something with it, the collector will be available at each iteration, that's why we use it to keep information of the data, in our case, it's the sum of the values. Once all the item has been iterated over, the function returns the collector.
<?php
$array = [
[
'1111' => [
'one' => 70,
'two' => 7.0
]
],
[
'1111' => [
'one' => 10,
'two' => 2.0
]
]
];
$output = array_reduce($array, function($collector, $item) {
$collector['1111']['one'] += $item['1111']['one'];
$collector['1111']['two'] += $item['1111']['two'];
return $collector;
}, ['1111' => ['one' => 0, 'two' => 0]]);
var_dump($output);
Here is an approach that uses a recursive merge. In the following when merged John's hours become an array. We then need to sum. As James only has one entry his hours do not become an array so we leave them be.
Hopefully the transitional merge output, will give you an idea of the process:
<?php
$items =
[
[
'john' => [
'hours' => 2,
'tips' => 7
]
],
[
'john' => [
'hours' => 3,
'tips' => 10
]
],
[
'james' => [
'hours' => 8,
'tips' => 0
]
]
];
$output = array_merge_recursive(...$items);
var_export($output);
array_walk($output, function(&$v) {
array_walk($v, function(&$v) {
if(is_array($v))
$v = array_sum($v);
});
});
echo "\nResult: \n";
var_export($output);
Output:
array (
'john' =>
array (
'hours' =>
array (
0 => 2,
1 => 3,
),
'tips' =>
array (
0 => 7,
1 => 10,
),
),
'james' =>
array (
'hours' => 8,
'tips' => 0,
),
)
Result:
array (
'john' =>
array (
'hours' => 5,
'tips' => 17,
),
'james' =>
array (
'hours' => 8,
'tips' => 0,
),
)
$total=0;
array_map(function ($item) use ($total)
{
$total += $item['one'] + $item['two'];
}, $array);
echo $total;
Or difference key
$one = array_sum(array_column($array, 'one'));
$two = array_sum(array_column($array, 'two'));
$resultArray = compact('one','two');
```
I need help merging two PHP arrays:
Array 1:
Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => 6
)
Array 2:
Array
(
[0] => Array
(
[id_sabor] => 2
[chocolate] => N
)
[1] => Array
(
[id_sabor] => 3
[chocolate] => S
)
[2] => Array
(
[id_sabor] => 4
[chocolate] => N
)
[3] => Array
(
[id_sabor] => 5
[chocolate] => S
)
[4] => Array
(
[id_sabor] => 6
[chocolate] => N
)
)
The values on array 1 are the active objects. I need to keep on Array 2 or on a new array only the ones with an [id_sabor] that matches in the array 1 (in this case: 2, 3, 4 and 6). Also, on those that [chocolate]=S add a new value: [costo_extra]=25.
One way to do that could be to use array_reduce and use in_array to check if the first array contains the value of id_sabor.
$array1 = [2, 3, 4, 6];
$array2 = [
["id_sabor" => 1, "chocolate" => "N"],
["id_sabor" => 2, "chocolate" => "N"],
["id_sabor" => 3, "chocolate" => "S"],
["id_sabor" => 4, "chocolate" => "N"],
["id_sabor" => 5, "chocolate" => "S"],
["id_sabor" => 6, "chocolate" => "N"]
];
$array2 = array_reduce($array2, function($carry, $item) use ($array1){
if (in_array($item["id_sabor"], $array1)) {
if ($item["chocolate"] === "S") {
$item["costo_extra"] = 25;
}
$carry[] = $item;
}
return $carry;
});
Demo
I am trying to filter an associative array so that certain values within a specific key will go into a specific variable. To make sense of this, here is an example of what I'm trying to do:
Input (from DB):
Array
(
[0] => Array
(
[id] => '12',
[status] => '0'
)
[1] => Array
(
[id] => '13',
[status] => '1'
)
[2] => Array
(
[id] => '14',
[status] => '1'
)
)
Output (in PHP):
$status_one =
Array
(
[0] => Array
(
[id] => '13',
[status] => '1'
)
[1] => Array
(
[id] => '14',
[status] => '1'
)
);
$status_zero =
Array
(
[0] => Array
(
[id] => '12',
[status] => '0'
)
)
I know that the arrays are not syntactically correct, but that's the idea. I want to split one variable of arrays into two separate variables based on the value in a specific key.
Here's what I have right. I know it's partly wrong. I've tried something with array_filter as well.
foreach ($status as $key => $row) {
if($row['status'] == '1')
{
$status_one[] = $key[$row];
}
if($row['status'] == '2')
{
$status_two[] = $key[$row];
}
}
You're close..
$status_one = array();
$status_zero = array();
foreach ($status as $key => $row) {
if($row['status'] == '1') $status_one[$key] = $row;
else $status_zero[$key] = $row;
}
var_dump($status_one, $status_zero);
If you do not like the if-else statements and prefer a more generic way of sorting by status, e.g if status is suddenly 2
$input = array(
array("id" => 1, "status" => 1),
array("id" => 2, "status" => 1),
array("id" => 3, "status" => 0),
array("id" => 4, "status" => 2),
array("id" => 5, "status" => 0)
);
$arr = array();
foreach($input as $key => $item){
$arr[$item['status']][] = $item;
}
ksort($arr, SORT_NUMERIC);
$arr would now be a multidimensional array sorted by status.
<?php list($status_zero, $status_one, $status_two) = $arr ?>
To assign the individual arrays to their own variable.
hope this helps...i think simple way is always the best...
function array_group(Array $array, $groupBy){
$grouped_array = [];
for ($i=0; $i<count($array); $i++){
$key_name = $groupBy.'_'.$array[$i][$groupBy];
if (!array_key_exists($key_name, $grouped_array)){
$grouped_array[$key_name] = [];
}
$grouped_array[$key_name][] = $array[$i];
}
return $grouped_array;
}
test :
$test_array = [["id" => 12, "status" => 0], ["id" => 13, "status" => 1], ["id" => 14, "status" => 1]];
print_r(array_group($test_array, 'status'));
output:
Array
(
[status_0] => Array
(
[0] => Array
(
[id] => 12
[status] => 0
)
)
[status_1] => Array
(
[0] => Array
(
[id] => 13
[status] => 1
)
[1] => Array
(
[id] => 14
[status] => 1
)
)
)
I have 2 arrays:
Array ( [0] => Array ( [intTrackId] => 41 [intAverageRating] => 10 [bolNewRelease] => 0 [dtDateAdded] => 2013-03-08 17:32:26 ) [1] => Array ( [intTrackId] => 1 [intAverageRating] => 7 [bolNewRelease] => 0 [dtDateAdded] => 2013-03-08 18:54:35 ))
Array ( [0] => Array ( [intTrackId] => 41 [intAverageRating] => 5.5000 [bolNewRelease] => 1 [dtDateAdded] => 2014-03-25T09:39:28Q ) [1] => Array ( [intTrackId] => 361 [intAverageRating] => 8.0000 [bolNewRelease] => 1 [dtDateAdded] => 2014-03-25T09:39:28Q ))
I want to remove the items in the second which have a matching track ID in the first. So in this example, I would get:
Array ( [0] => Array ( [intTrackId] => 361 [intAverageRating] => 8.0000 [bolNewRelease] => 1 [dtDateAdded] => 2014-03-25T09:39:28Q ))
Is this possible with array_filter or is this a little complex for that?
Just use array_udiff() - it's intended to do this:
$one = Array (
0 => Array ('intTrackId' => 41, 'intAverageRating' => 10, 'bolNewRelease' => 0, 'dtDateAdded' => '2013-03-08 17:32:26' ),
1 => Array ('intTrackId' => 1, 'intAverageRating' => 7, 'bolNewRelease' => 0, 'dtDateAdded' => '2013-03-08 18:54:35' )
);
$two = Array (
0 => Array ('intTrackId' => 41, 'intAverageRating' => 5.5000, 'bolNewRelease' => 1, 'dtDateAdded' => '2014-03-25T09:39:28Q' ),
1 => Array ('intTrackId' => 361, 'intAverageRating' => 8.0000, 'bolNewRelease' => 1, 'dtDateAdded' => '2014-03-25T09:39:28Q' )
);
$result = array_udiff($two, $one, function($x, $y)
{
return $x['intTrackId']-$y['intTrackId'];
});
Yes it can be done with array_filter:
$array1 = array(...);
$array2 = array(...);
$newArray = array_filter($array2, function($item) use ($array1){
foreach($array1 as $elem){
if($item['intTrackId'] == $elem['intTrackId']){
return false;
}
}
return true;
});
I would first create a loop and store all track IDs from the first array in a separate array.
Then I'd loop over the second array and delete those keys that exist in the track ID array.
$track_ids = array();
foreach($array1 as $index => $items) {
$track_ids[$items['intTrackId']] = $index;
}
foreach($array2 as $items) {
if (isset($track_ids[$items['intTrackId']])) {
unset($array2[$track_ids[$items['intTrackId']]]);
}
}