Janaka Dombawela
Janaka Dombawela

Reputation: 1357

Intersect (inner join) two arrays with different key names

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?

Upvotes: 2

Views: 1424

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

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

Upvotes: 3

Related Questions