Get duplicate and unique data between two multi-dimensional arrays - php

There's a lot of questions out there that deals between arrays and multi-dimensional arrays but only one so how about two then? Let's say this is the data:
Array
(
[0] => Array
(
[BRANCHCODE] => 2
[BRANCH] => BRANCH 1
[AGREEID] => 1
)
[1] => Array
(
[BRANCHCODE] => 2
[BRANCH] => BRANCH 2
[AGREEID] => 2
)
[2] => Array
(
[BRANCHCODE] => 2
[BRANCH] => BRANCH 3
[AGREEID] => 3
)
)
Array
(
[0] => Array
(
[BRANCHCODE] => 2
[BRANCH] => BRANCH 4
[AGREEID] => 1
)
[1] => Array
(
[BRANCHCODE] => 2
[BRANCH] => BRANCH 5
[AGREEID] => 4
)
[2] => Array
(
[BRANCHCODE] => 2
[BRANCH] => BRANCH 6
[AGREEID] => 5
)
)
I managed to get the duplicated data but I can't get the unique data. Here's the php code on how I got the duplicates and also the count of the duplicated data.
In here I loop through both of the two arrays the first one is the array of the uploaded data and the next loop is the database results. I compared the two arrays if the AGREEID in the uploaded data has duplicate in the database. If the AGREEID in the uploaded data is unique I will insert it in the database.
foreach ($result as $key=>$upload_data) {
$agreeid_upload = $result[$key]['AGREEID'];
$data = $result[$key];
$another_data = $result[$key];
foreach ($reports as $dbase_data) {
$agreeid = $dbase_data->AGREEID;
if($agreeid_upload == $agreeid){ /// record has duplicate in the database
$count_duplicates = $count_duplicates + 1;
$duplicates[$key] = $data;
}else{
///here i want to store into another array the unique data..
}
}
}

The method used would work, but is going to be inefficient with a large amount of data because it will do a lot of extra looping.
$dbAgreeeData = array();
$duplicates = array();
$unique = array();
foreach ($reports as $dbase_data) {
$dbAgreeeData[$db_dbase_data->AGREEID] = $dbase_data;
}
foreach ($result as $key=>$upload_data) {
$agreeId = $upload_data['AGREEID'];
if (isset($dbAgreeeData[$agreeId)){
$duplicates[$agreeId] = $upload_data;
}
else {
$unique[$agreeId] = $upload_data;
}
}
$numDuplicate = count($duplicates);
$numUnique = count($unique);
Or
$dbAgreeeData = array();
$uploadData= array();
foreach ($reports as $dbase_data) {
$dbAgreeeData[$db_dbase_data->AGREEID] = $dbase_data;
}
foreach ($result as $key=>$upload_data) {
$uploadData[$upload_data['AGREEID']] = $upload_data;
}
$duplicates = array_intersect_key($dbAgreeData, $uploadData;
$unique = array($dbAgreeData, $uploadData);
$numDuplicate = count($duplicates);
$numUnique = count($unique);

Related

Combining Arrays while merging the values with the same key

I have two arrays with same amount of values. I need to combine them ( array1 value to key, array2 value as value) without losing the values of the second array due to duplicate key. when I use combine_array() as expected it just gets the last value of the second array with the same key.
Array
(
[0] => 1
[1] => 2
[2] => 2
[3] => 3
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
)
Desired result
Array
(
[1] => 1
[2] => Array(
[0]=>2
[1]=>3
)
[3] => 2
)
This code will meet your request
$array1 = array("0"=>1,"1"=>2,"2"=>2,"3"=>3);
$array2 = array("0"=>1,"1"=>2,"2"=>3,"3"=>4);
$array = array();
foreach($array1 as $key => $value){
if($value != $array2[$key]){
$array[$key][] = $value;
$array[$key][] = $array2[$key];
}else{
$array[$key] = $value;
}
}
print_r($array);
The desired result is
Array
(
[0] => 1
[1] => 2
[2] => Array
(
[0] => 2
[1] => 3
)
[3] => Array
(
[0] => 3
[1] => 4
)
)
I'm sure there are way better solutions than this, but it does the job for now. I would appreciate if someone can send a better written solution.
$combined = array();
$tempAr = array();
$firstMatch = array();
$count = 0;
foreach ($array1 as $index => $key) {
if (array_key_exists($key, $combined)) {
$tempAr[] = $array2[$index];
$count++;
} else {
$totalCount = $count;
}
if (!array_key_exists($key, $firstMatch)) {
$firstMatch[$key] = $array2[$index];
}
$output = array_slice($tempAr, $totalCount);
$combined[$key] = $output;
}
$combined = array_merge_recursive($firstMatch, $combined);

Combine values by key in single array

Nothing really does exactly what I want to achieve. I have the following array:
Array(
[0] => Array
(
[chicken] => 7
)
[1] => Array
(
[cheese] => 9
)
[2] => Array
(
[marinade] => 3
)
[3] => Array
(
[cookbook] => 7
)
[4] => Array
(
[chicken] => 11
)
[5] => Array
(
[cheese] => 6
)
[6] => Array
(
[marinade] => 12
)
)
I want to sum all values by their key. If the key is multiple times in the array, like chicken, I want to sum the values.
array
(
[chicken] => 18,
[cheese] => 16
... etc
)
So you'd first need a loop to iterate through the first array to get the second-level arrays. Then you can get the current key and value from each of those arrays, summing the values in a new array associated by the key.
// where the sums will live
$sum = [];
foreach($array as $item) {
$key = key($item);
$value = current($item);
if (!array_key_exists($key, $sum)) {
// define the initial sum of $key as 0
$sum[$key] = 0;
}
// add value to the sum of $key
$sum[$key] += $value;
}
Here simple example i hope it's help you.
$result = array();
foreach($data as $key => $value)
{
$valueKey = key($value);
$result[$valueKey] += $value[$valueKey];
}

Average result of multidimensional array in PHP

This is a question for all the array specialists out there. I have an multi dimension array with a result as number (can be 0,1 or 2) and need the average for each grouped by parent.
In the example below the calculation would be:
subentry1_sub1 = 2 + 2 = 4 (4/2=2)
subentry1_sub2 = 1 + 1 = 2 (2/2=1)
So what I try to archive in PHP is the following result:
subentry1_sub1 average = 2
subentry1_sub2 average = 1
...
I already tried some solutions from similar questions. But with all the recursive functions I didn't managed to get it aggregated by the last child name (e.g. subentry1_sub1).
Any ideas?
EDIT:
subentry1_sub1 is 2 + 2 because its two times in the array
[entry1] => [subentry1] => [subentry1_sub1] => result
[entry2] => [subentry1] => [subentry1_sub1] => result
Array
(
[entry1] => Array
(
[subentry1] => Array
(
[subentry1_sub1] => Array
(
[value] => abc
[result] => 2
)
[subentry1_sub2] => Array
(
[value] => abc
[result] => 1
)
)
[subentry2] => Array
(
[subentry2_sub1] => Array
(
[value] => abc
[result] => 1
)
[subentry2_sub2] => Array
(
[value] => abc
[result] => 1
)
)
)
[entry2] => Array
(
[subentry1] => Array
(
[subentry1_sub1] => Array
(
[value] => abc
[result] => 2
)
[subentry1_sub2] => Array
(
[value] => abc
[result] => 1
)
)
[subentry2] => Array
(
[subentry2_sub1] => Array
(
[value] => abc
[result] => 1
)
[subentry2_sub2] => Array
(
[value] => abc
[result] => 1
)
)
)
)
Try this code. In this i have created a new array $sum which will add result value of same subentry childs with same key and another array $count which will count the number of times each key repeats
<?php
$data = array('entry1'=>array(
'subentry1'=>
array(
'subentry1_sub1'=>array('value'=>'abc','result'=>2),
'subentry1_sub2'=>array('value'=>'abc','result'=>1)
),
'subentry2'=>
array(
'subentry2_sub1'=>array('value'=>'abc','result'=>1),
'subentry2_sub2'=>array('value'=>'abc','result'=>1)
)
),
'entry2'=>array(
'subentry1'=>
array(
'subentry1_sub1'=>array('value'=>'abc','result'=>2),
'subentry1_sub2'=>array('value'=>'abc','result'=>1)
),
'subentry2'=>
array(
'subentry2_sub1'=>array('value'=>'abc','result'=>1),
'subentry2_sub2'=>array('value'=>'abc','result'=>1)
)
)
);
$sum = array();
$repeat = array();
foreach($data as $input){
foreach($input as $array){
foreach($array as $key=>$value){
if(array_key_exists($key,$sum)){
$repeat[$key] = $repeat[$key]+1;
$sum[$key] = $sum[$key] + $value['result'];
}else{
$repeat[$key] = 1;
$sum[$key] = $value['result'];
}}}}
echo "<pre>";
print_r($sum);
print_r($repeat);
foreach($sum as $key=>$value){
echo $key. ' Average = '. $value/$repeat[$key]."</br>";
}
Output
Array
(
[subentry1_sub1] => 4
[subentry1_sub2] => 2
[subentry2_sub1] => 2
[subentry2_sub2] => 2
)
Array
(
[subentry1_sub1] => 2
[subentry1_sub2] => 2
[subentry2_sub1] => 2
[subentry2_sub2] => 2
)
subentry1_sub1 Average = 2
subentry1_sub2 Average = 1
subentry2_sub1 Average = 1
subentry2_sub2 Average = 1
You can easily calculate avg now
Note : As you mentioned you are counting occurence of subentry1_sub1 etc so i did the same so it will also count whether key result exists or not
I know this is an old thread but im pretty sure there is a much easier way of doing this for anyone who is interested:
If you know the result will always be a number:
foreach($my_array as $entry_name => $entry_data)
{
foreach($entry_data as $sub_name => $sub_data)
{
$sub_results = array_column($sub_data, 'result');
$averages[$entry_name][$sub_name] = array_sum($sub_results)/count($sub_results);
}
}
If its possible the result could be NULL or empty, this will check it and return 'N/A' if there is no valid data to calculate an average from:
foreach($my_array as $entry_name => $entry_data)
{
foreach($entry_data as $sub_name => $sub_data)
{
$sub_results = array_filter(array_column($sub_data, 'result'));
$averages[$entry_name][$sub_name] = (count($sub_results) > 0 ? array_sum($sub_results)/count($sub_results) : 'N/A');
}
}
both of these solutions will give you an averages array that will output the average per subentry per entry.
Try this like,
<?php
$data=array('entry1'=>array(
'subentry1'=>
array(
'subentry1_sub1'=>array('value'=>'abc','result'=>3),
'subentry1_sub2'=>array('value'=>'abc','result'=>3)
),
'subentry2'=>
array(
'subentry2_sub1'=>array('value'=>'abc','result'=>2),
'subentry2_sub2'=>array('value'=>'abc','result'=>8)
)
),
'entry2'=>array(
'subentry1'=>
array(
'subentry1_sub1'=>array('value'=>'abc','result'=>6),
'subentry1_sub2'=>array('value'=>'abc','result'=>6)
),
'subentry2'=>
array(
'subentry2_sub1'=>array('value'=>'abc','result'=>10),
'subentry2_sub2'=>array('value'=>'abc','result'=>12)
)
)
);
foreach($data as $k=>$v){
echo "----------------$k---------------------\n";
if(is_array($v)){
foreach($v as $a=>$b){
if(is_array($b)){
echo $a.' average = ';
$c=array_keys($b);// now get *_sub*
$v1=isset($b[$c[0]]['result']) ? $b[$c[0]]['result'] : '';
$v2=isset($b[$c[1]]['result']) ? $b[$c[1]]['result'] : '';
echo ($v1+$v2)/2;
echo "\n";
}
}
}
}
Online Demo
In the meantime I found a simple working solution myself:
foreach ($data as $level2) {
foreach ($level2 as $level3) {
foreach ($level3 as $keyp => $level4) {
foreach ($level4 as $key => $value) {
if($key == 'result') $stats[$keyp] += $value;
}
}
}
}
With that you get the total for every key in an new array $stats.
But be sure to checkout the solution from user1234, too. It's working great and already includes the calculation of the average.
https://stackoverflow.com/a/39292593/2466703

Get total for value in arrays

I am trying to find a way to allow me to count the number of times a value appears across multiple arrays as well as, for each unique value, the total count.
The data looks like the below:
Array ( [id] => 4383 [score] => 3 )
Array ( [id] => 4382 [score] => 4 )
Array ( [id] => 4381 [score] => 5 )
Array ( [id] => 4383 [score] => 7 )
Array ( [id] => 4383 [score] => 1 )
Array ( [id] => 4382 [score] => 2 )
Array ( [id] => 4381 [score] => 8 )
The above should return:
4383 - 3 - 11
4382 - 2 - 6
4381 - 2 - 13
I have used array_push and created one array called $output and looped using foreach to get a count of the id's using:
foreach($output as $row) {
$array[$row[0]]++;
}
This returns the correct count of id but I cannot get the total score for each id - I have tried:
foreach($output as $row) {
foreach($row as $r) {
$array[$row[0]]=$array[$row[1]]+$array[$r[1]];
}
}
but it returns zero for everything
Like below:
$result = array();
foreach ($data as $value) {
if (!isset($result[$value['id']])) {
$result[$value['id']] = array('count' => 0, 'sum' => 0);
}
$result[$value['id']]['count'] += 1;
$result[$value['id']]['sum'] += $value['score'];
}
$result = array();
foreach ($output as $row) {
if (!array_key_exists($row[0], $result)) {
$result[$row[0]] = array("Count" => 1, "Total" => $row[1]);
}
else {
$result[$row[0]]['Count'] += 1;
$result[$row[0]]['Total'] += $row[1];
}
}
print_r($result);

Combining two arrays PHP

I'm busy with sorting the structure of a menu in my application. Once the menu is reorderd by the user, the values (say; Menu item 1, Menu item 2, etc) are still in the same place.
Now I have two arrays, one that holds the way they are sorted (Array 1) and one that holds the values of the menu items. (Array 2)
Example of both arrays;
(Array 1, that holds the keys)
Array
(
[0] => 1
[1] => 2
[2] => 0
)
The above array's values are the keys for the new array.
(Array 2, holds the values)
Array
(
[0] => value_0
[1] => value_1
[2] => value_2
)
So I thought it would be best to create a new array which consist out of;
The values of Array 1
The values of Array 2
However, i'm running into a problem. I want the values in array 2 to stick to their keys. So lets say I change the position of value_0 to the last, the new array would look like this;
Array
(
[1] => value_1
[2] => value_2
[0] => value_0
)
Is there a way to achieve this or am I doing it completely wrong?
Edit
Ok, so multidemensional array it is. However i'm having problems creating one.
Array 1 and Array 2 both come from the database. Array 1 with the sorting order and Array 2 contains the values. Now, the values in array 2 are stored like this; value1,value2,value3. So to be able to work with them I explode on , (comma).
The results on the fetchs are both different;
For the first array it returns as many as how many values there are.
(So if there are 3 values, it will return 3 different positions.)
For the second array it will return 18 records, since this is tied to
other menu items (sub menu's etc).
So for the first array I do;
while ($row = mysql_fetch_assoc($result_query_test)) {
$positions[] = $row['position'];
}
For the second array I do;
while ($row = mysql_fetch_assoc($result_values)) {
$array_values = explode(',', $row['values']);
}
From then on i'm having problems creating the multidimensinonal array;
while ($row = mysql_fetch_assoc($result_values)) {
$array_values = explode(',', $row['values']);
foreach ($positions as $new_key) {
foreach ($array_values as $value) {
$new_array[] = array('key' => $new_key, 'value' => $value);
}
}
}
Edit two:
This is what I use now;
(Since $all_values is a multidimensional array because I have to explode on the values beforehand.)
foreach ($all_values as $values) {
foreach ($values as $key => $value) {
$new_array[] = array('key' => $positions[$key], 'value' => $value);
}
}
This is what the $new_array returns;
Array
(
[0] => Array
(
[key] => 0
[value] => value_0
)
[1] => Array
(
[key] => 2
[value] => value_2
)
[2] => Array
(
[key] => 1
[value] => value_1
)
[3] => Array
(
[key] => 0
[value] => value_0
)
[4] => Array
(
[key] => 2
[value] => value_2
)
[5] => Array
(
[key] => 1
[value] => value_1
)
Now I need to get the values and implode them with comma's. However, since not every 3 values (value_0, value_1, value_3) are together I can't do that now.
In this example there are 3 keys, (0,1,2) which should be a different array along with their values, like you did in your example:
Array (
[0] = Array (
[key] = 1,
[value] = value_1
),
[1] = Array (
[key] = 2,
[value] = value_2
),
[2] = Array (
[key] = 0,
[value] = value_0
)
)
Why not make a multidimensional array?
$arrayThree =
Array (
[0] = Array (
[key] = 1,
[value] = value_1
),
[1] = Array (
[key] = 2,
[value] = value_2
),
[2] = Array (
[key] = 0,
[value] = value_0
)
)
No matter what order they're in, the key and value are always the set.
foreach ($arrayThree as $tempArray)
{
echo $tempArray['key'];
echo $tempArray['value'];
}
Create Array
$arrayOne = array();
$arrayTwo = array();
$arrayThree = array();
$query = 'SELECT key FROM table1 ';
$result = mysql_query($query) or die(mysql_error());
while($data = mysql_fetch_assoc($result))
{
$arrayOne[] = $data['key'];
}
$query = 'SELECT value FROM table2 ';
$result = mysql_query($query) or die(mysql_error());
while($data = mysql_fetch_assoc($result))
{
$arrayTwo[] = $data['value'];
}
foreach($arrayOne as $key => $value)
{
$arrayThree[] = array('key' => $value, 'value' => $arrayTwo[$key]);
}
You can always use the mysqli or PDO versions, if you're using them.
Example Data
//THESE MIMIC YOUR SELECT RESULTS
$test_keys = array(1,2,3);
$test_values = array('value_1', 'value_2', 'value_3');
//DEFAULTS
$arrayOne = array();
$arrayTwo = array();
$arrayThree = array();
//WHILE FIRST SELECT
for($i=0;$i<count($test_keys);$i++)
{
$arrayOne[] = $test_keys[$i];
}
//WHILE SECOND SELECT
for($i=0;$i<count($test_values);$i++)
{
$arrayTwo[] = $test_values[$i];
}
//MAKE THE FINAL ARRAY
foreach($arrayOne as $key => $value)
{
$arrayThree[] = array('key' => $value, 'value' => $arrayTwo[$key]);
}
//CHECK THE OUTPUT FOR THE NEW ARRAY
echo '<pre>'.print_r($arrayThree,true).'</pre>';
Example Output
Array
(
[0] => Array
(
[key] => 1
[value] => value_1
)
[1] => Array
(
[key] => 2
[value] => value_2
)
[2] => Array
(
[key] => 3
[value] => value_3
)
)
Imploded List
$implodeValues = array_map(function($item) { return $item['value']; }, $arrayThree);
$implodeVariable = implode(',', $implodeValues);
echo $implodeVariable;
Implode Output
value_1,value_2,value_3
I think you can obtain what you want doing this:
$new = array();
for($i = 0, $len = count($array1), $i < $len, ++$i) {
$new[$array1[$i]] = $array2[$i];
}
now $new contains the values in the order you want them

Categories