php array find duplicates, sum them up & delete duplicates - php

i have an array:
Array
(
[0] => Array
(
[setid] => 2
[income] => 100
)
[1] => Array
(
[setid] => 2
[income] => 120
)
[2] => Array
(
[setid] => 3
[income] => 700
)
)
i need to find entrys with the same setid, sum their income up and delete duplicate entrys - in the end it should look like this:
Array
(
[0] => Array
(
[setid] => 2
[income] => 220
)
[1] => Array
(
[setid] => 3
[income] => 700
)
)
does someone know a sophosticated solution for my problem or do i have to take the long road and do every step manually?
thanks and greetings

Just create a new array which you make fast adressable by using the setid as key. And reindex the array at the end.
$result = array();
foreach ($array as $val) {
if (!isset($result[$val['setid']]))
$result[$val['setid']] = $val;
else
$result[$val['setid']]['income'] += $val['income'];
}
$result = array_values($result); // reindex array

This should work:
$values = array();
foreach($array as $val) {
if(isset($values[$val['setid']])) {
$values[$val['setid']] += $val['income'];
} else {
$values[$val['setid']] = $val['income'];
}
}
//all values are now in $values array, keys are setid and values are income

Write your own function, that's no long road at all.
$result = array_reduce($originalArray, function($memo, $item){
isset($memo[$item['setid']])
? $memo[$item['setid']] = $item['income']
: $memo[$item['setid']] += $item['income'];
return $memo;
}, []);

You should use the array_unique function that php's official site offers.
An example:
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
Output:
Array
(
[a] => green
[0] => red
[1] => blue
)
To sum the duplicated values you can use the array_count_values function:
<?php
$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));
?>
Output would be:
Array
(
[1] => 2
[hello] => 2
[world] => 1
)

Related

Remove duplicate array on the base of key in multidimendional array PHP [duplicate]

This question already has answers here:
How to remove duplicate values from a multi-dimensional array in PHP
(18 answers)
Closed 6 years ago.
From following array key with ID 16 is comming twice. Hown can we remove this this duplicate ID. (REMOVE IF ID IS DUPLICATE OTHER FIELDS IGNORE)
Array
(
[1] => Array
(
[ID] => 16
[username] => dudda
[message-time] => 2016-08-25 12:12:53
)
[2] => Array
(
[ID] => 16
[username] => dudda
[message-time] => 2016-08-25 12:01:54
)
[3] => Array
(
[ID] => 3
[username] => himanshu
[message-time] => 2016-08-15 12:53:38
)
[4] => Array
(
[ID] => 15
[username] => dawinder
[message-time] => 2016-08-10 11:40:33
)
)
I Got solution
I have develop this function for same :
function unique_multidim_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
Now, call this function anywhere from your code,
something like this,
$details = unique_multidim_array($array_name,'key');
We used this to de-duplicate results from a variety of overlapping queries.
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
Read this:http://php.net/manual/en/function.array-unique.php
For Example
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
Output will be:
Array
(
[a] => green
[0] => red
[1] => blue
)

Combine two different dimensional arrays PHP

I have two different dimensional arrays.
Array 1:
Array1
(
[0] => Array
(
[id] => 123
[price] => 5
[purchase_time] => 2014/4/10
)
[1] => Array
(
[id] => 123
[price] => 5
[purchase_time] => 2014/5/17
)
)
Array 2:
Array2
(
[0] => 5
[1] => 8
)
I want something like this:
Array
(
[0] => Array
(
[id] => 123
[price] => 5
[purchase_time] => 2014/4/10
[Qty] => 5
)
[1] => Array
(
[id] => 123
[price] => 5
[purchase_time] => 2014/5/17
[Qty] => 8
)
)
Basically the first array is the information I got from a SQL table. The second array contains the quantity for the products sold. I now want to combine these two array together and use the combined array to create a new table. Since these two arrays have different dimensions. I'm not sure how to do it. Here is my try:
$i = 0;
foreach($array1 as $row)
{
$newarray = array_merge($row,$array2[$i]);
$i++;
}
Might be a simpler way, but for fun without foreach:
array_walk($array1, function(&$v, $k, $a){ $v['Qty'] = $a[$k]; }, $array2);
The simplest way is:
$i = 0;
foreach($array1 as &$row) {
$row['Qty'] = $array2[$i++];
}
Or if keys of both arrays are the same (0,1,2...) and array have the same length:
foreach($array1 as $k => &$row) {
$row['Qty'] = $array2[$k];
}
If the $array1 and $array2 are mapped by the same indexes, so they have same length, you can try:
foreach($array2 as $index=>$quantity){
$array1[$index]['Qty'] = $quantity;
}
And it´s done!
If you want to keep the original $array1 untouched, you can make a copy before the foreach.
Create new array and store it there. You can access the value of $array2 because they have the same index of $array1 so you can use the $key of these two arrays.
$array3 = [];
foreach($array1 as $key => $val) {
$array3[] = [
'id' => $val['id'],
'price' => $val['price'],
'purchase_time' => $val['purchase_time'],
'Qty' => $array2[$key]
];
}
print_r($array3);

Push data to elements in array in php

$array = array(array("a"=>1),array("a"=>2));
I need to push data to sub array element in $array,
End result must be as follow,
Array ( [0] => Array ( [a] => 1 [b] => 2 ) [1] => Array ( [a] => 2 [b] => 2 ) )
I used following ways .
foreach($array as &$a){ $a['b']=2;}
$result = array_map("pushdata",$array);
function pushdata($a){
$a['b']=2;
}
what is the most suitable and performance high way when $array consists of more than 1000 records ?
Here is an example using array_walk() to add a new key b to each sub-array:
$array = array(array('a' => 1), array('a' => 2));
array_walk($array, function(&$item, $key) {
$item['b'] = 2;
});
print_r($array);
/* outputs:
Array
(
[0] => Array
(
[a] => 1
[b] => 2
)
[1] => Array
(
[a] => 2
[b] => 2
)
)
*/
Here is an example for 5 items.
<?php
for($i = 1 ; $i<5 ; $i++){
$array[] = array("a"=>$i,"b"=>2);
}
print_r($array);
?>
See online
Use array_walk , to iterate over the array and array_push to push the element to each iteration.

Combine two arrays into a single array based on a common column value

I am trying to combine two arrays while respecting their shared value.
$array1 = array(
array("id" => "1","name"=>"John"),
array("id" => "2","name"=>"Peter"),
array("id" => "3","name"=>"Tom"),
array("id" => "12","name"=>"Astro")
);
$array2 = array(
array("id" => "1","second_name"=>"Lim"),
array("id" => "2","second_name"=>"Parker"),
array("id" => "3","second_name"=>"PHP")
);
My expected output:
$result = array(
array("id" => "1","name"=>"John","second_name"=>"Lim"),
array("id" => "2","name"=>"Peter","second_name"=>"Parker"),
array("id" => "3","name"=>"Tom","second_name"=>"PHP"),
array("id" => "12","name"=>"Astro")
);
I have made a try by
$arraycomb = array_unique(array_merge($array1,$array2), SORT_REGULAR);
My output is:
Array
(
[0] => Array
(
[id] => 1
[name] => John
)
[1] => Array
(
[id] => 2
[name] => Peter
)
[2] => Array
(
[id] => 3
[name] => Tom
)
[3] => Array
(
[id] => 12
[name] => Astro
)
[4] => Array
(
[id] => 1
[second_name] => Lim
)
[5] => Array
(
[id] => 2
[second_name] => Parker
)
[6] => Array
(
[id] => 3
[second_name] => PHP
)
)
How can I combine the key value inside same array? or how can I bring the expected output?
Note: I am trying for value instead of key ref: PHP Array Merge two Arrays on same key
Alternatively, you could use a foreach in this case then merge them if they share the same id key
With using reference &
foreach($array1 as &$value1) {
foreach ($array2 as $value2) {
if($value1['id'] == $value2['id']) {
$value1 = array_merge($value1, $value2);
}
}
}
echo '<pre>';
print_r($array1);
You can use array_map() for this. Try this -
function modifyArray($a, $b)
{
if (!empty($a) && !empty($b)) {
return array_merge($a, $b);
} else if (!empty($a) && empty($b)) {
return $a;
} else if (empty($a) && !empty($b)) {
return $b;
}
}
$new = array_map("modifyArray", $array1, $array2);
var_dump($new);
It will generate the new array will all the values in both arrays.if the first array's element is empty then the second array will be merged and vice-versa.
Assign temporary first level keys to your first array to aid in identifying rows. Then loop the second array and append the desired column value to the appropriate group. Re-index the array after looping with array_values().
Code: (Demo)
$result = array_column($array1, null, 'id');
foreach ($array2 as $row) {
$result[$row['id']]['second_name'] = $row['second_name'];
}
var_export(array_values($result));
This is a more direct approach than brute force scanning arrays with nested loops.
If all ids in the second array exist in the first array, then the following simpler line can be written inside the body of the foreach().
$result[$row['id']] += $row;

Handling multi-dimensional PHP Array

I have arrays of fonts with their name and weight e.g.
print_r($fontarray1);
Array (
[font] => Open+Sans
[weight] => normal
)
print_r($fontarray2);
Array (
[font] => Open+Sans
[weight] => bold
)
print_r($fontarray3);
Array (
[font] => Lato
[weight] => bolditalic
)
I have many arrays of fonts $fontarray1, $fontarray2, $fontarray3.. I want to make one final array of fonts and their weights.. for example, if "Open+Sans" is already in the final array, it should not be added, but if "Open+Sans" is in final Array with a different "weight" then only the "weight" should be added alongwith the "Open+Sans" key.. the expected result should be something like:
Array (
[font] => Oen+Sans
[weight] => Array (
[0] => normal
[1] =>bold
)
[font] => Lato
[weight] => Array (
[0] => bolditalic
)
)
I tried something like below, but confused on how to add another array within one array..:
$final_arr = Array();
if (!in_array($fontarray1['font'], $final_arr)) {
$final_arr []= $fontarray1['font'];
} else {
// already in array, lets check font weight
}
}
any help or thought would be highly appreciated. cheers
First
Use array_merge
<?php
$beginning = 'foo';
$end = array(1 => 'bar');
$result = array_merge((array)$beginning, (array)$end);
print_r($result);
?>
Second
Use array_unique
<?php
$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);
?>
Look` like structure like this can be usefull for you:
Array(
"fontName" => Array(
[weight] => Array(
[0] => "normal"
)
)
)
And your function would be like
$final_arr = Array();
$fontName = $fontarray1['font'];
$fontWeight = $fontarray1['weight'];
if (!isset($final_arr[$fontName])) {
$final_arr[$fontName] = array('weight' => $fontWeight);
} else {
$final_arr[$fontName]['weight'][] = $fontWeight;
}
You're just trying to add $fontarray1 to $final_arr?
$final_arr[] = $fontarray1
Creating a multidimensional array:
$theArray = array();
$theArray[] = array('key1'=>'val1', 'key2'=>'val2'); // creates a subarray

Categories