[英]Common values in two arrays
I have two arrays - 我有两个数组-
$x = [['email' => 'abc@gmail.com', 'id' => [1,2,3]],
['email' => 'xyz@gmail.com', 'id' => [4,5]]]
$y = ['email' => 'abc@gmail.com']
I have to return the common email in both the sets along with the ids in $x
array. 我必须同时返回这两个集合中的通用电子邮件以及
$x
数组中的ID。
The output should be - 输出应为-
$z = [['email' => 'abc@gmail.com', 'id' => [1,2,3]]
How to do it? 怎么做?
array_intersect
? array_intersect
? But for array_intersect
both arrays should have same number of keys. 但是对于
array_intersect
两个数组应具有相同数量的键。
You need to do it in traditional way by using foreach loop: 您需要使用foreach循环以传统方式进行操作:
$x = [
['email' => 'abc@gmail.com', 'id' => [1, 2, 3]],
['email' => 'xyz@gmail.com', 'id' => [4, 5]]
];
$y = array('email' => 'abc@gmail.com');
$z = array();
foreach($x as $arr){
if(in_array($arr['email'],$y) !== false){
$z[] = $arr;
}
}
print_r($z);
Output: 输出:
Array
(
[0] => Array
(
[email] => abc@gmail.com
[id] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
)
You can use array_filter()
with an anonymous function, passing to it a needle value by use
directive: 您可以将
array_filter()
与匿名函数一起使用,并通过use
指令将其指针值传递给它:
$x = [
['email' => 'abc@gmail.com', 'id' => [1,2,3]],
['email' => 'xyz@gmail.com', 'id' => [4,5]]
];
$y = ['email' => 'abc@gmail.com'];
$matched = array_filter($x, function($item) use($y) {
return $item['email'] === $y['email'];
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.