How to intersect Array of objects in PHP? - php

How do i get the result of intersection between two Array of Objects in PHP.
For Example,
the value of $array1 is
Array
(
[0] => stdClass Object
(
[id] => 2
[influencer_id] => 2
[follower_id] => 1
)
)
and the value of $array2 is,
Array
(
[0] => stdClass Object
(
[id] => 2
[influencer_id] => 1
[follower_id] => 2
),
[1] => stdClass Object
(
[id] => 3
[influencer_id] => 3
[follower_id] => 2
),
)
So, what i want to get in $result is
Array
(
[0] => stdClass Object
(
[id] => 2
[influencer_id] => 2
[follower_id] => 1
)
)
What is the best way to get it?
Thanks in advance!

You can do that using array_uintersect function and defining manually your callback comparison function :
$arr1 = json_decode('[{"id":2,"influencer_id":2,"follower_id":1}]');
$arr2 = json_decode('[{"id":2,"influencer_id":2,"follower_id":1},{"id":3,"influencer_id":3,"follower_id":2}]');
$arr3 = array_uintersect($arr1, $arr2, function ($e1, $e2) {
if($e1->id == $e2->id && $e1->influencer_id == $e2->influencer_id && $e1->follower_id == $e2->follower_id) {
return 0;
} else {
return 1;
}
});
var_dump($arr3);

Try to use array_intersect
array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.

Related

Check if array contain other array (for multidimensional array) php [duplicate]

This question already has answers here:
PHP: Check if an array contains all array values from another array
(5 answers)
Closed 4 years ago.
I am looking forward to compare two arrays in PHP.
For example, I have array A:
Array
(
[0] => Array
(
[option_id] => 19
[sub_option_id] => 57
)
[1] => Array
(
[option_id] => 1093
[sub_option_id] => 3582
)
[2] => Array
(
[option_id] => 1093
[sub_option_id] => 57
)
)
And array B:
Array
(
[0] => Array
(
[order_option_detail] => Array
(
[0] => Array
(
[option_id] => 19
[sub_option_id] => 57
)
[1] => Array
(
[option_id] => 1093
[sub_option_id] => 57
)
[2] => Array
(
[option_id] => 1093
[sub_option_id] => 3582
)
)
)
[1] => Array
(
[order_option_detail] => Array
(
[0] => Array
(
[option_id] => 1
[sub_option_id] => 2
)
)
)
)
By looking at the data structure, I can see that array B contains array A. How can I achieve the same analysis using PHP, ie how to check array B contain array A?
Please help me if you know!
Thank you so much!
You can use the following function for array compare:
function array_equal($a, $b) {
if (!is_array($a) || !is_array($b) || count($a) != count($b))
return false;
$a = array_map("json_encode", $a);
$b = array_map("json_encode", $b);
return array_diff($a, $b) === array_diff($b, $a); // mean both the same values
}
And then use it as:
$details = array_column($arrayB, 'order_option_detail');
foreach($details as $detail){ // loop the two items.
if (array_equal($detail, $arrayA)) {
// Do what ever
}
}
From arrayB you only need 'order_option_detail'.
So if we use array_column we can get those isolated.
$details = array_column($arrayB, 'order_option_detail');
foreach($details as $detail){ // loop the two items.
if($detail === $arrayA){
// Do something
}
}
https://3v4l.org/TW670

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;

How to sort 2 arrays by the value [duplicate]

This question already has answers here:
How to Sort a Multi-dimensional Array by Value
(16 answers)
Closed 7 years ago.
I have this array:
Array (
[order] => Array ( [0] => 2 [1] => 1 )
[eventid] => Array ( [0] => id_1 [1] => id_2 )
)
Now I would like to get:
Array (
[order] => Array ( [0] => 1 [1] => 2 )
[eventid] => Array ( [0] => id_2 [1] => id_1 )
)
Basically I would like to sort arrays by value of order.
You will need to use the usort function to be able to do this. (See the documentation)
I would recommend another Array structure though, something like this:
Array (
[0] => Array ( [order] => 2, [eventid] => id_x )
[1] => Array ( [order] => 1, [eventid] => id_y )
)
Then you could a function like this one to sort your array (PHP 5.3 or greater):
function array_sort_by(&$array, $key, $descending = false) {
$sortByKey =
function ($a, $b) use ($key, $descending) {
if ($a[$key] === $b[$key]) {
return 0;
}
$return = $a[$key] < $b[$key] ? -1 : 1;
return ($descending ? -1 * $return : $return);
};
usort($array, $sortByKey);
}
You would then call the following:
array_sort_by($yourArray, 'order');
You can use asort. While it can cover your case, usort might be a better solution in the long run.
$arr = Array (
"order" => Array ( 0 => 6, 1 => 1,2=>43),
"eventid" => Array ( 0 => 5, 1 => 1,2=>54,3=>0)
);
foreach ($arr as $key => &$value) {
asort($value);
}

make a particular element to be first in array

I've an array like this
$arrList = Array (
[0] => Array
(
[master] => Array
(
[id] => 3
[name] => Test
)
)
[1] => Array
(
[master] => Array
(
[id] => 4
[name] => Sample
)
)
)
Now, I know the value of the id,how can I re-arrange with the particular value of id to be on the top..(i.e.,whatever the value of id that I have in a variable that should be on top of the array, if I get the value of id as 4 then the array should be
$arrList = Array (
[0] => Array
(
[master] => Array
(
[id] => 4
[name] => Sample
)
)
[1] => Array
(
[master] => Array
(
[id] => 3
[name] => Test
)
)
)
thanks in advance..
Just try this code
foreach($arrList as $Key => $array) {
if($id == $array['master']['id']){ //check the value with all [master][id]
$arr[] = $array; // setting up the respective array to another array
$iKey = $Key; // getting the key value of that particular array
}
}
if(isset($iKey) && $iKey != NULL){
unset($arrList[$iKey]); // removing the key value from the main array
array_splice($arrList, 0, 0, $arr);
//using this function setting up again the array to the 0th index,
}
for any other index value, mention as second parameter in above function, suppose if you need to have as third index then it should be..
array_splice($arrList, 3, 0, $arr);
function cmp($a, $b)
{
if ($a['master']['id'] == $b['master']['id']) {
return 0;
}
return ($a['master']['id'] > $b['master']['id']) ? -1 : 1;
}
$a = Array (
0 => Array (
'master' => Array
(
'id' => 3,
'name' => 'Test',
)
),
'1' => Array
(
'master' => Array
(
'id' => 4,
'name' => 'Sample',
)
)
);
usort($a, "cmp");
print_r($a);
You can sort the array with a special sort function. The code is:
usort($array, function($a,$b){ return $b['master']['id']==4; });
Try this, I have created example here
http://codepad.org/z4oI9KHk

PHP array sort using inner val

Array
(
[1] => Array
(
[id] => 1
[sort] => 1
)
[3] => Array
(
[id] => 3
[sort] => 3
)
[2] => Array
(
[id] => 2
[sort] => 2
)
)
How do i sort it so its re-ordered using the inner 'sort' key ? ie the above would look like this:
Array
(
[1] => Array
(
[id] => 1
[sort] => 1
)
[2] => Array
(
[id] => 2
[sort] => 2
)
[3] => Array
(
[id] => 3
[sort] => 3
)
)
You can use usort with this comparison function:
function cmpBySort($a, $b) {
return $a['sort'] - $b['sort'];
}
usort($arr, 'cmpBySort');
Or you use array_multisort with an additional array of key values for the sort order:
$keys = array_map(function($val) { return $val['sort']; }, $arr);
array_multisort($keys, $arr);
Here array_map with the anonymous function is used to build an array of the sort values that is used to sort the array values itself. The advantage of this is that there is np comparison function that needs to be called for each pair of values.
Something like this:
usort($array, function (array $a, array $b) { return $a["sort"] - $b["sort"]; });
Something like this:
uasort($array, 'compfunc');
function compfunc($a, $b)
{
return $a['sort'] - $b['sort'];
}

Categories