通过特定键将多个多维数组相交,并获得来自两个数组的所有数据的结果

intersect multiple multi-dimensional arrays by a specific key and get result with all data from both arrays

我正在尝试获取数组与其包含更多数据的自身子集的交集。结果应包括两个数组中的所有字段。

给出的例子:

   $arr1 = [
       ['id' => 1, 'country' => 'US', 'user_name' => 'test1'],
       ['id' => 2, 'country' => 'UK', 'user_name' => 'test2'],
       ['id' => 3, 'country' => 'IT', 'user_name' => 'test3']
    ];

    $arr2 = [
        ['cid' => 1, 'orders' => 100, 'views' => 3 ],
        ['cid' => 3, 'orders' => 200, 'views' => 4 ],
    ];

结果应该是:

       $res = [
           ['id' => 1, 'country' => 'US', 'user_name' => 'test1', 'orders' => 100, 'views' => 3 ],
           ['id' => 3, 'country' => 'IT', 'user_name' => 'test3', 'orders' => 200, 'views' => 4 ],
       ];

我尝试使用 array_uintersect_uassoc 如图所示

        $result = array_uintersect_uassoc($arr1, $arr2, function ($a, $b) {
           return strcasecmp($a['id'], $b['cid']);
        }, function ($a, $b) {
           return (int)[$a, $b] == ['id', 'cid'];
        });

但结果不包括第二个数组中的字段。

在我的例子中,第二个数组 cid 键是第一个数组的 id 键的子集。

我想要一种有效的方法来获得所需的结果。

您只需循环第二个数组并检查第一个数组。如果元素存在于第一个中,则使用 array_merge:

合并在一起
<?php
   $arr1 = [
       ['id' => 1, 'country' => 'US', 'user_name' => 'test1'],
       ['id' => 2, 'country' => 'UK', 'user_name' => 'test2'],
       ['id' => 3, 'country' => 'IT', 'user_name' => 'test3']
    ];

    $arr2 = [
        ['cid' => 1, 'orders' => 100, 'views' => 3 ],
        ['cid' => 3, 'orders' => 200, 'views' => 4 ],
    ];
    $arr1 = array_column($arr1, null, 'id'); // Index by ID
    $arr2 = array_column($arr2, null, 'cid'); // Index by CID

    $arr3 = []; // Results array. Possible to merge back to $arr1 too

    foreach ($arr2 as $id => $a2) {
        if (isset($arr1[$id])) {
            $arr3[] = array_merge($arr1[$id], $a2);
        }
    }

    var_dump($arr3);

Example