Intersect (inner join) two arrays with different key names

谁说胖子不能爱 提交于 2020-08-24 03:17:32

问题


I have following two multidimensional arrays:

First array:

$array_1_data = Array (
    [0] => Array ( [id] => 1 [name] => IT [slug] => it )
    [1] => Array ( [id] => 2 [name] => Accounting [slug] => accounting )
)

Second array:

$array_2_data = Array (
    [0] => Array ( [cid] => 3 [jid] => 24061 )
    [1] => Array ( [cid] => 1 [jid] => 24062 )
)

Expected result:

$some_array = Array (
    [0] => Array ( [id] => 1 [name] => IT [slug] => it )
)

I won't mind having [cid] in the result.

I want to intersect these two arrays by [id] of the first array and [cid] of the second array, like inner join in MySQL. I have basic foreach and if else logic for this purpose but speed is a priority now so I'm looking for non-looped solution. For better understanding here is the basic looped solution:

    foreach ($array_1_data as $array_1_row ) {
        foreach ($array_2_data  as $array_2_row ) {
            if ($array_2_row['cid'] == $array_1_row['id']) {
                //intersection iteration
            }
        }
    }

I tried array_uintersection as follows:

array_uintersect($array_1_data, $array_2_data, function($a1, $a2){
    $diff1 = strcasecmp($a1['id'], $a2['cid']);
    if ($diff1 != 0) return $diff1;
    return 0;
});

But it gives me undefined index 'id'. I checked this question: Comparing two arrays with different key names. First answer for this question gives a looped solution which I want to avoid. Second answer suggests changing SQL structure but I have no control over that. So,

Is there really a non-looped fast solution to this kind of situation?


回答1:


The solution using array_uintersect_uassoc function:

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

print_r($result);

The output:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => IT
            [slug] => it
        )
)

According yo your condition: to intersect these two arrays by [id] of the first array and [cid] of the second array, we should consider a key comparison function for those keys only ['id', 'cid'].
Having the needed keys on each comparison step it only remain to compare their values(with value compare function)

http://php.net/manual/en/function.array-uintersect-uassoc.php

DEMO link



来源:https://stackoverflow.com/questions/39383195/intersect-inner-join-two-arrays-with-different-key-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!