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

问题描述 投票:0回答:1

我试图得到一个数组与一个包含更多数据的数组子集的交集。结果应该包括两个数组的所有字段。

举个例子。

   $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'];
        });

但结果并不包括第2个数组的字段。

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

我想得到一个有效的方法来得到想要的结果。

php php-7
1个回答
1
投票

你需要简单地循环第二个数组并检查第一个数组。如果元素存在于第一个数组中,则使用 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);

例子

© www.soinside.com 2019 - 2024. All rights reserved.