Merge duplicate values in array [duplicate] - php

This question already has answers here:
How to group subarrays by a column value?
(20 answers)
Closed 5 months ago.
I have this result from a foreach loop.
I tried looping through the array using foreach from the answers in StackOverflow, but I'm having trouble when doing it under another foreach loop.
Array
(
[0] => Array
(
[referenceUid] => FF875951-87CB-942F-84A2-46C620BF07C8
[itemUid] => 4CD23391-AD8C-C2FB-EF4A-46093D8A37AE
[total] => 300.00
)
)
Array
(
[0] => Array
(
[referenceUid] => D267A795-E142-C25B-E042-D8A519B57DF4
[itemUid] => 4CD23391-AD8C-C2FB-EF4A-46093D8A37AE
[total] => 150.00
)
)
Array
(
[0] => Array
(
[referenceUid] => D267A795-E142-C25B-E042-D8A519B57DF4
[itemUid] => 4CD23391-AD8C-C2FB-EF4A-46093D8A37AE
[total] => 150.00
)
)
What I want is to merge the array with duplicate values on referenceUid column. Something like this:
Array
(
[0] => Array
(
[referenceUid] => FF875951-87CB-942F-84A2-46C620BF07C8
[itemUid] => 4CD23391-AD8C-C2FB-EF4A-46093D8A37AE
[total] => 300.00
)
)
Array
(
[0] => Array
(
[referenceUid] => D267A795-E142-C25B-E042-D8A519B57DF4
[itemUid] => 4CD23391-AD8C-C2FB-EF4A-46093D8A37AE
[total] => 150.00
)
[1] => Array
(
[referenceUid] => D267A795-E142-C25B-E042-D8A519B57DF4
[itemUid] => 4CD23391-AD8C-C2FB-EF4A-46093D8A37AE
[total] => 150.00
)
)

You can construct a new (merged) array and loop your input to assemble the new structure.
An important consideration is to use the common key (referenceUid) as the array key in your new array so you can reference it easily. If you don't want it at the end, simply reset the array keys e.g. $out = array_values($out).
Here's an example:
$output = array();
foreach ($input as $values) {
$key = $values['referenceUid'];
$output[$key][] = $values;
}
// Don't want the referenceUid in the keys? Reset them:
$output = array_values($output);
Example

//both arrays will be merged including duplicates
$result = array_merge( $array1, $array2 );
//duplicate objects will be removed
$result = array_map("unserialize", array_unique(array_map("serialize", $result)));
//array is sorted on the bases of id
sort( $result );`

Related

PHP add values from multidimensional array into one array [duplicate]

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 7 months ago.
If I have an array $array like this:
Array (
[0] => Array (
[id] => 11
[name] => scifi
)
[1] => Array (
[id] => 12
[name] => documetary
)
[2] => Array (
[id] => 10
[name] => comedy
)
)
How could I turn it into simply:
Array ( 11, 12, 10 ) with no key value pairs.
I am trying to extract only the id from each array and add them into 1 array. I am trying it with a foreach;
$ids = [];
if ( $array ) {
foreach ( $array as $item ) {
$ids[] = $term->id;
}
}
print_r($ids);
It just returns 3 empty arrays Array ( [0] => [1] => [2] => )
Using a loop, you can do this:
$arr1 = [
['id'=>11,'name'=>'scifi'],
['id'=>12,'name'=>'documentry'],
['id'=>10,'name'=>'comedy'],
];
$arr2 = [];
foreach($arr1 as $internal){
array_push($arr2,$internal['id']);
}
print_r($arr2);
Here we access all internal array's ID's and insert them into a new array.

I want to change the key of multidimensional array [duplicate]

This question already has answers here:
How do you reindex an array in PHP but with indexes starting from 1?
(12 answers)
Closed 3 years ago.
I want to change the key of the multidimensional array. the array contains key like 1,15,23,45 which should be replaced by normal index key like 0,1,2,3. I tried with below code. Something is missing in below code. Please, anyone, suggest to me.
$keys = array_keys($data);
$d = 0;
foreach($data as $row){
$key_data[$d] = $data[$keys[$d]];
unset($row[$keys[$d]]);
$d++;
}
Current Output
Array
(
[15] => Array
(
[0] => Array
(
[app_dealer_id] => 15
[dealer_name] => Sharad Thombre
[shopname] => Shivshankar Fertilizer
[contact_num] => 9049121143
[district] => Parbhani
)
)
[18] => Array
(
[0] => Array
(
[app_dealer_id] => 18
[dealer_name] => Gajanan Khapre
[shopname] => Shreyas Krishi Kendra
[contact_num] => 8007791946
[district] => Parbhani
)
)
)
Expected Output:
Array
(
[0] => Array
(
[0] => Array
(
[app_dealer_id] => 15
[dealer_name] => Sharad Thombre
[shopname] => Shivshankar Fertilizer
[contact_num] => 9049121143
[district] => Parbhani
)
)
[1] => Array
(
[0] => Array
(
[app_dealer_id] => 18
[dealer_name] => Gajanan Khapre
[shopname] => Shreyas Krishi Kendra
[contact_num] => 8007791946
[district] => Parbhani
)
)
)
use array_values()
$array = array_values($array);
Output:-https://3v4l.org/cUAdl
From php.net :
array_values() returns all the values from the array and indexes the array numerically.
So just add it after your loop to reindex you array :
$keys = array_keys($data);
$d = 0;
foreach($data as $row){
$key_data[$d] = $data[$keys[$d]];
unset($row[$keys[$d]]);
$d++;
}
$newArray = array_keys($key_data);

PHP - Merge Two Associative Arrays where values match [duplicate]

This question already has answers here:
Array merge on key of two associative arrays in php?
(2 answers)
Closed 9 months ago.
I have two arrays that need to be merged. I can loop through each array and merge manually. But, Is there a built in function to do this?
Array 1:
Array
(
[0] => Array
(
[detail_image_id] => 6389
[product_name] => Starter broadband Package
)
[1] => Array
(
[detail_image_id] => 6358
[product_name] => Starter broadband Package
)
)
Array 2:
Array
(
[0] => Array
(
[detail_image_id] => 6358
[guid] => http://xxx/wp-content/uploads/2018/04/broadband-4mbs-wingle.jpg
)
[1] => Array
(
[detail_image_id] => 6389
[guid] => http://xxx/wp-content/uploads/2018/04/broadband-4mbs-charji.jpg
)
)
Expected Output array is:
Array
(
[0] => Array
(
[detail_image_id] => 6389
[product_name] => Starter broadband Package
[guid] => http://xxx/wp-content/uploads/2018/04/broadband-4mbs-charji.jpg
)
[1] => Array
(
[detail_image_id] => 6358
[product_name] => Starter broadband Package
[guid] => http://xxx/wp-content/uploads/2018/04/broadband-4mbs-wingle.jpg
)
)
I have added only a sample from the array. Array is huge. Is there any PHP functions like array_merge() or array_map() that we can use instead of manual for loops and iterators?
Older & wiser: I've scrubbed my answer from years earlier because I no longer recommend the techniques. It will be most succinct and efficient to merge the arrays, feed them to a foreach() loop, then "unite" (+ is used as an array union operator) data in related rows.
The null coalescing operator (??) is used to ensure that there is always something to "unite" with.
Code: (Demo)
$result = [];
foreach (array_merge($array1, $array2) as $row) {
$result[$row['detail_image_id']] = ($result[$row['detail_image_id']] ?? []) + $row;
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'detail_image_id' => '6389',
'product_name' => 'Starter broadband Package',
'guid' => 'http://xxx/wp-content/uploads/2018/04/broadband-4mbs-charji.jpg',
),
1 =>
array (
'detail_image_id' => '6358',
'product_name' => 'Starter broadband Package',
'guid' => 'http://xxx/wp-content/uploads/2018/04/broadband-4mbs-wingle.jpg',
),
)
You can do something like:
$arr1 = array(); //Your array 1
$arr2 = array(); //Your array 2
//Make a temp array to that use detail_image_id as the key
$arr1Temp = array_combine( array_column($arr1,'detail_image_id'), $arr1 );
$arr2Temp = array_combine( array_column($arr2,'detail_image_id'), $arr2 );
//Get All unique detail_image_id from 2 arrays.
//This is to make sure that all detail_image_id's will be included.
//detail_image_id on 2nd array might not be present on the 1st one
$imgIds = array_unique(array_merge( array_keys($arr1Temp), array_keys($arr2Temp) ));
//Do a simple foreach loop
$result = array();
foreach( $imgIds as $val ) {
$result[] = array_merge( $arr1Temp[$val], $arr2Temp[$val] );
}
print_r( $result );
This will result to:
Array
(
[0] => Array
(
[detail_image_id] => 6389
[product_name] => Starter broadband Package
[guid] => http://xxx/wp-content/uploads/2018/04/broadband-4mbs-charji.jpg
)
[1] => Array
(
[detail_image_id] => 6358
[product_name] => Starter broadband Package
[guid] => http://xxx/wp-content/uploads/2018/04/broadband-4mbs-wingle.jpg
)
)
You can use a combination of array_column() and array_combine() to create a reference array using the detail_image_id as key. Then, with a foreach() loop, you can merge arrays using + operator:
$array1 = [
['detail_image_id' => '6389', 'product_name' => 'Starter broadband Package'],
['detail_image_id' => '6358', 'product_name' => 'Starter broadband Package']
];
$array2 = [
['detail_image_id' => '6358', 'guid' => 'http://xxx/wp-content/uploads/2018/04/broadband-4mbs-wingle.jpg'],
['detail_image_id' => '6389', 'guid' => 'http://xxx/wp-content/uploads/2018/04/broadband-4mbs-charji.jpg']
];
// create associative array with detail_image_id as key,
$out = array_combine(array_column($array1, 'detail_image_id'), $array1);
foreach ($array2 as $item) {
$key = $item['detail_image_id']; // shortcut for the key,
$out[$key] = $out[$key] + $item; // merge arrays
}
print_r(array_values($out)); // reset to indexed keys (0,1,2...)
Output:
Array
(
[0] => Array
(
[detail_image_id] => 6389
[product_name] => Starter broadband Package
[guid] => http://xxx/wp-content/uploads/2018/04/broadband-4mbs-charji.jpg
)
[1] => Array
(
[detail_image_id] => 6358
[product_name] => Starter broadband Package
[guid] => http://xxx/wp-content/uploads/2018/04/broadband-4mbs-wingle.jpg
)
)

Removing subarrays that share a key-value pair with another multidimensional array

I have 2 arrays as below. I want to remove data from array2 if array1 has the stu_id. final array should be like result_array.
$array1 = Array
(
[0] => Array
(
[stu_id] => 1
[name] => mr.a
)
[1] => Array
(
[stu_id] => 3
[name] => mr.b
)
)
$array2 = Array
(
[0] => Array
(
[id] => 1
[stu_id] => 1
[data] => abc
)
[1] => Array
(
[id] => 2
[stu_id] => 2
[data] => xyz
)
[3] => Array
(
[id] => 3
[stu_id] => 3
[data] => aaa
)
)
$result_array = Array
(
[0] => Array
(
[id] => 2
[stu_id] => 2
[data] => xyz
)
)
I tried array_diff, $result_array = array_diff($array2, $array1); but it's not working.
Please help me to do this.
Temporarily assign keys using array_column() with stud_id (NULL retains the full subarray data), then use array_diff_key() to filter, and array_values() to reset the keys:
Code: (Demo)
$array1=[
['stu_id'=>1,'name'=>'mr.a'],
['stu_id'=>3,'name'=>'mr.b']
];
$array2=[
['id'=>1,'stu_id'=>1,'data'=>'abc'],
['id'=>2,'stu_id'=>2,'data'=>'xyz'],
['id'=>3,'stu_id'=>3,'data'=>'aaa']
];
//var_export(array_column($array1,NULL,'stu_id'));
//var_export(array_column($array2,NULL,'stu_id'));
var_export(array_values(array_diff_key(array_column($array2,NULL,'stu_id'),array_column($array1,NULL,'stu_id'))));
Output:
array (
0 =>
array (
'id' => 2,
'stu_id' => 2,
'data' => 'xyz',
),
)
If you'd like to use a foreach loop structure, generate a filtering array of stu_id's from $array1 and write a conditional check on each iteration of $array2. This method doesn't not modify the original arrays, so they can be reused "down script".
Code:
$stu_ids=array_column($array1,'stu_id');
foreach($array2 as $row){
if(!in_array($row['stu_id'],$stu_ids)){
$result[]=$row; // auto-index the qualifying subarrays
}
}
var_export($result);
// same result as above method
foreach($array1 as $data1){
foreach($array2 as $k => $data2){
if($data2["stu_id"] == $data1["stu_id"]){
unset($array2[$k]);
break;
}
}
}
$result_array = $array2;

Merge array values in a single array by removing duplicates and null values in PHP

I have an array like this:
Array
(
[0] => Array
(
[0] => Array
(
[id] => 1234
[name] => John
)
[1] => Array
(
)
)
[1] => Array
(
[0] => Array
(
[id] => 1234
[name] => John
)
[1] => Array
(
[id] => 5678
[name] => Sally
)
[2] => Array
(
[id] => 1234
[name] => Duke
)
)
My resulting array should be the following (basically merging and getting rid of duplicates and removing null values):
Array
(
[0] => Array
(
[id] => 1234
[name] => John
)
[1] => Array
(
[id] => 5678
[name] => Sally
)
[2] => Array
(
[id] => 1234
[name] => Duke
)
)
Is there an easy way to do this using PHP's array functions?
EDIT: So far I have this:
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, $value);
}
}
print_r($result);
Use array_merge to merge the arrays. Then use array_unique to remove duplicates. Finally, to remove null keys, use a loop.
foreach($array as $key=>$value)
{
if(is_null($value) || $value == '')
unset($array[$key]);
}
Documentation on these methods can be found here.
Flatten your unnecessarily depth array structure by unpacking the subarrays into a merge call.
Filter out the empty subarrays with array_filter().
Remove the duplicate subarrays with array_unique(). (SORT_REGULAR prevents "Warning: Array to string conversion")
Code: (Demo)
var_export(
array_unique(
array_filter(
array_merge(...$array)
),
SORT_REGULAR
)
);
Optionally, call array_values() on the resultant array to re-index it (remove the old keys).

Categories