PHP在两个多维数组中查找相同的值,并将它们映射到单独的数组中

时间:2018-11-04 19:55:15

标签: php multidimensional-array

我有两个多维数组:

Array (
[1] => Array
    (   
    [id] => 1 
    [email] => aaa@mail.com

    some irrelevant pairs
    )

[2] => Array
    (
    [id] => 2 
    [email] => bbb@mail.com

    some irrelevant pairs
    )

[3] => Array
    (
    [id] => 3 
    [email] => ccc@mail.com

    some irrelevant pairs
    ))

Array (
[1] => Array
    (   
    [id] => 4 
    [email] => aaa@mail.com

    some irrelevant pairs
    )

[2] => Array
    (
    [id] => 5 
    [email] => bbb@mail.com

    some irrelevant pairs
    )

[3] => Array
    (
    [id] => 6 
    [email] => ccc@mail.com

    some irrelevant pairs
    ))

如您所见,它们都具有相同值的键“ email”。如何将ID对作为键值对在单独的数组中提取为同一封电子邮件的映射?我尝试了foreach循环和in_array函数,但是出了点问题。这就是我需要的:

Result (pairs of IDs where e-mail values are the same: my_array_with_pairs_of_IDs = ( "1" => "4", "2" => "5", "3" => "6" );

请帮助,非常感谢!

3 个答案:

答案 0 :(得分:2)

您可以使用array_column制作两个可以使用array_search的平面阵列。
如果array_search返回的结果不是false,则为找到的匹配项的键。

$arr1 = array_column($arr1, 'email', 'id');
$arr2 = array_column($arr2, 'email', 'id');

foreach($arr1 as $key => $val){
    $find = array_search($val, $arr2);
    if($find !==false) $result[$key] = $find;
}
var_dump($result);

输出:

array(3) {
  ["1 "]=>
  string(2) "4 "
  ["2 "]=>
  string(2) "5 "
  ["3 "]=>
  string(2) "6 "
}

https://3v4l.org/6XhUd

答案 1 :(得分:2)

基于@Andreas答案,性能得到优化:

$map1 = array_column($arr1, 'id', 'email');
$map2 = array_column($arr2, 'id', 'email');

$result = [];

foreach ($map1 as $email => $id)
{
    if (isset($map2[$email]))
    {
        $result[$id] = $map2[$email];
    }
}
  • 删除了$arr1$arr2的覆盖;
  • 添加了$result声明。

答案 2 :(得分:1)

您可以使用此方法并将数据存储在新数组中

$result = [];
foreach($a1 as $a){
   foreach($b1 as $b){
      if($b[email] == $a[email])
         $result[] = [$a[id]=>$b[id]];
   }
}