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

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;

Related

Merge a simple array and nested array according to same keys

I have array 1 like this
Array
(
[0] => 1
[1] => 2
)
Second array would be
Array
(
[0] => Array
(
[FullName] => Bhupat Chippa
)
[1] => Array
(
[FullName] => Dvs Patel
)
)
I want to merge it the way values would be added to second array with same keys. Desired Output will look like this or some way around so that I can use the Array 1's value with Second Array Only:
Array
(
[0] => Array
(
[FullName] => Bhupat Chippa
[0] => 1
)
[1] => Array
(
[FullName] => Dvs Patel
[1] => 2
)
)
You can apply simple foreach() to do that
$final = [];
foreach($array2 as $key =>$arr2 ){
$final[$key]['FullName'] = $arr2['FullName'];
$final[$key][$key] = $array1[$key];
}
print_r($final);
Output:- https://eval.in/1010437
If both arrays are of the same length, you might use array_map passing the array_keys as the second parameter:
$array1 = ["1", "2"];
$array2 = [
["FullName" => "Bhupat Chippa"],
["FullName" => "Dvs Patel"]
];
$result = array_map(function($x, $y) use ($array1){
$x[$y] = $array1[$y];
return $x;
}, $array2, array_keys($array1));
print_r($result);
Demo
That will give you:
Array
(
[0] => Array
(
[FullName] => Bhupat Chippa
[0] => 1
)
[1] => Array
(
[FullName] => Dvs Patel
[1] => 2
)
)

PHP using one array as keys for subarray of multidimensional array

So i got one single dimensional array like:
Array
(
[0] => md5
[1] => name
[2] => description
[3] => url
)
and one multidimensional array:
Array
(
[0] => Array
(
[0] => md5#1
[1] => name1
[2] => desc1
[3] => url1
)
[1] => Array
(
[0] => md5#2
[1] => name2
[2] => desc2
[3] => url2
)
)
and I want to use values of first array as keys for subarrays of the multidimensional one, so the output should look like:
Array
(
[0] => Array
(
[md5] => md5#1
[name] => name1
[desription] => desc1
[url] => url1
)
[1] => Array
(
[md5] => md5#2
[name] => name2
[description] => desc2
[url] => url2
)
)
Alternatively(as a bit offtopic question), how can I sort the elements of multidimensional array by values of md5 if they keys of subarray are not [md5] but [0]?
Thanks in advance!
For combining values of two arrays where values of one are keys, and values of other are values, use array_combine function:
$keysArray = [];
$multiArray = [];
$result_array = [];
foreach ($multiArray as $value) {
$result_array[] = array_combine($keysArray, $value);
}
For sorting - use usort and define your custom function:
usort($result_array, function($a, $b) { return strcmp($a['md5'], $b['md5']); });
Here is the functional-style equivalent of #u_mulder's answer.
This technique merely applies the array of key names as the keys for every row in the array.
Using arrow function syntax (available since PHP7.4), allows the custom callback to access the globally scoped $keys array without needing to explicitly write use($keys) in the function declaration.
Code: (Demo)
$first = ['md5#1', 'name1', 'description1', 'url1'];
$second = ['md5#2', 'name2', 'description2', 'url2'];
$multidimArray = [$first, $second];
$keys = ['md5', 'name', 'description', 'url'];
var_export(
array_map(
fn($row) => array_combine($keys, $row),
$multidimArray
)
);

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).

Need common arrays from two multidimensional arrays

Hi I have below multidimensional arrays -
Array
(
[user_attempts] => 0
[2] => Array
(
[0] => 1
[1] => 4
)
[3] => Array
(
[0] => 32
[1] => 23
)
[4] => Array
(
[0] => asdsa
)
[1] => Array
(
[0] => Earth
)
)
and my second array is like below
Array
(
[1] => Array
(
[0] => Earth
)
[2] => Array
(
[0] => 2
[1] => 3
)
[3] => Array
(
[0] => 32
[1] => 23
)
[4] => Array
(
[0] => asdsa
[1] => asdas
)
)
I need to intersect both multidimensional arrays - so the result would be
Array
(
[1] => Array
(
[0] => Earth
)
[3] => Array
(
[0] => 32
[1] => 23
)
)
Can anyone help me to sort this out.
What I have tried is using array_intersect() but it limits to single array not multidimensional i guess.
PHP comes with a ton of functions already built in, but sometimes you still have to implement things yourself. What you want to do can be easily done by using the existing functions.
The goal is to do the following steps:
Find the keys that exist in both arrays
Loop through the array using these keys
Take the items of both input arrays with each of these keys
Calculate the intersection of those two arrays
Put it into a result array
Here is one way to do this:
function array_intersect_2dim (array $a1, array $a2) {
$keys = array_intersect(array_keys($a1), array_keys($a2));
$return = array();
foreach ($keys as $key) {
$return[$key] = array_intersect($a1[$key], $a2[$key]);
if (sizeof($return[$key]) == 0) {
unset($return[$key]);
}
}
return $return;
}
It works only for two dimensions. If you need more, you have to build a recursive approach, which follows the exact same principle.
To make the easier to compare you can use serialize/unserialize on this one. And then use array_intersect(). Try this example: Sample Output
$array1 = array( 'user_attemps' => 0, 2 => array(1, 4), 3 => array(32, 23), 4 => array('asdsa'), 1 => array('Earth'),);
$array2 = array( 1 => array('Earth'), 2 => array(2, 3), 3 => array(32, 23), 4 => array('asdsa', 'asdas'),);
$result = array_map('unserialize',array_intersect(array_map('serialize', $array1), array_map('serialize', $array2)));
print_r($result);

Merge two object arrays and remove duplicated objects then sort by column value

I have the following two arrays of objects:
First Array: $array1
Array
(
[0] => stdClass Object
(
[id] => 100
[name] => Muhammad
)
[1] => stdClass Object
(
[id] => 102
[name] => Ibrahim
)
[2] => stdClass Object
(
[id] => 101
[name] => Sumayyah
)
)
Second Array: $array2
Array
(
[0] => stdClass Object
(
[id] => 100
[name] => Muhammad
)
[1] => stdClass Object
(
[id] => 103
[name] => Yusuf
)
)
I want to merge these two object arrays (removing all duplicates) and sorted according to id.
Desired output:
Array
(
[0] => stdClass Object
(
[id] => 100
[name] => Muhammad
)
[1] => stdClass Object
(
[id] => 101
[name] => Sumayyah
)
[2] => stdClass Object
(
[id] => 102
[name] => Ibrahim
)
[3] => stdClass Object
(
[id] => 103
[name] => Yusuf
)
)
These 3 simple steps did the work:
//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 );
Note: Answer by #Kamran helped me come to this simple solution
UPDATE
I am posting the entire code listing here now instead of the previously posted main code, printing both input and output. You can simply copy and paste this code to test.
<?php
function array_to_object($arr) {
$arrObject = array();
foreach ($arr as $array) {
$object = new stdClass();
foreach ($array as $key => $value) {
$object->$key = $value;
}
$arrObject[] = $object;
}
return $arrObject;
}
function super_unique($array)
{
$result = array_map("unserialize", array_unique(array_map("serialize", $array)));
foreach ($result as $key => $value) {
if ( is_array($value) ) {
$result[$key] = super_unique($value);
}
}
return $result;
}
function merge_arrays($arr1, $arr2) {
$arr1 = (array)$arr1;
$arr2 = (array)$arr2;
$output = array_merge($arr1, $arr2);
sort($output);
return super_unique($output);
}
$array1 = array(
array("id" => "100", "name" => "muhammad"),
array("id" => "102", "name" => "ibrahim"),
array("id" => "101", "name" => "summayyah"),
);
$array1 = array_to_object($array1);
print "<h3>Your array 1</h3>";
print "<pre>";
print_r($array1);
print "</pre>";
$array2 = array(
array("id" => "100", "name" => "muhammad"),
array("id" => "103", "name" => "yusuf"),
);
$array2 = array_to_object($array2);
print "<h3>Your array 2</h3>";
print "<pre>";
print_r($array2);
print "</pre>";
$result = merge_arrays($array1, $array2);
print "<h3>Your desired output</h3>";
print "<pre>";
print_r($result);
print "</pre>";
it will output the following:
Your array 1
Array
(
[0] => stdClass Object
(
[id] => 100
[name] => muhammad
)
[1] => stdClass Object
(
[id] => 102
[name] => ibrahim
)
[2] => stdClass Object
(
[id] => 101
[name] => summayyah
)
)
Your array 2
Array
(
[0] => stdClass Object
(
[id] => 100
[name] => muhammad
)
[1] => stdClass Object
(
[id] => 103
[name] => yusuf
)
)
Your desired output
Array
(
[0] => stdClass Object
(
[id] => 100
[name] => muhammad
)
[2] => stdClass Object
(
[id] => 101
[name] => summayyah
)
[3] => stdClass Object
(
[id] => 102
[name] => ibrahim
)
[4] => stdClass Object
(
[id] => 103
[name] => yusuf
)
)
Assignments:
Merge
Remove Duplicates
Sort by id
The good news is: Assigning temporary keys using id values does all of the hard work for you. No serializing is needed.
array_merge() joins the arrays together.
array_column() with a null 2nd parameter leaves the objects unmodified and id as the 3rd parameter assigns the temporary keys. Because arrays cannot have duplicate keys, duplicate objects are weeded out in this step.
Now that we have keys, ksort() avoids calling the more convoluted usort() to sort by id ascending.
Finally, call array_values() to re-index the resultant array (remove the temporary keys).
Code: (Demo)
$array1 = [
(object) ['id' => 100, 'name' => 'Muhammad'],
(object) ['id' => 102, 'name' => 'Ibrahim'],
(object) ['id' => 101, 'name' => 'Sumayyah']
];
$array2 = [
(object) ['id' => 100, 'name' => 'Muhammad'],
(object) ['id' => 103, 'name' => 'Yusuf']
];
$merged_keyed = array_column(array_merge($array1,$array2), NULL, 'id');
ksort($merged_keyed);
var_export(array_values($merged_keyed));
Alternatively, you can filter one of the arrays to remove duplicates, then merge them, then sort them. sort() will effectively order the rows by the id column because the rows have equal size and id is the element in first position.
Code: (Demo)
$result = array_merge($array1, array_udiff($array2, $array1, fn($a, $b) => $a <=> $b));
sort($result);
var_export($result);

Categories