Reputation: 1515
I have a little problem. I have to compare arrays like this :
array(2) {
[0]=>
array(4) {
["persons"]=>
int(1)
["date"]=>
string(21) "2018-10-01 2018-11-14"
["type"]=>
string(7) "for one"
["sun"]=>
string(3) "yes"
}
[1]=>
array(4) {
["persons"]=>
int(2)
["date"]=>
string(21) "2018-10-01 2018-10-14"
["type"]=>
string(7) "for two"
["sun"]=>
string(3) "yes"
}}
And now I have options, which picked user for example :
array(2) {
["type"]=>
string(7) "for two"
["sun"]=>
string(3) "yes"
}
And now I have problem to compare these two arrays. I need records from first array only which are difference and match with the search variables from array two. I need result like this in this case :
array(1) {
[0]=>
array(2) {
["persons"]=>
int(2)
["date"]=>
string(21) "2018-10-01 2018-10-14"
}}
I tryed array_diff and array_intersect but this is not result what I need. I tryed also in foreach loop but I can't fix to get my target. Is there some ready php function to get this?
Upvotes: 1
Views: 53
Reputation: 11642
To have this in the most generic way you can use array_filter, array_diff and array_map
consider the following example:
$a = array("a" => "aaa", "b" => "bbb", "c" => "ddd");
$b = array("a" => "aaa", "b" => "bbb", "c" => "ccc");
$arr = array($a,$b); // this is your base array
$find = array("b" => "bbb", "c" => "ccc"); // this is as your options (what you want to find)
Now you can do:
$barr = array_filter($arr, function($elem) use ($find) {
return count(array_intersect($find, $elem)) == count($find);
}); // $barr contains only the sub-arrays that contains the option you wanted
$carr = array_map(function($elem) use ($find) {
return array_diff($elem, $find);
},$barr); // $carr contain only the field that are not in the option array
Now the $carr
is your desire output
Upvotes: 2