相交(内部联接)具有不同键名的两个数组 [英] Intersect (inner join) two arrays with different key names

查看:82
本文介绍了相交(内部联接)具有不同键名的两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下两个多维数组:

I have following two multidimensional arrays:

第一个数组:

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

第二个数组:

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

预期结果:

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

我不介意结果中包含[cid].

我想用第一个数组的[id]和第二个数组的[cid]相交这两个数组,就像MySQL中的内部联接一样.为此,我具有基本的foreachif else逻辑,但是现在速度是优先考虑的事情,因此我正在寻找非循环解决方案.为了更好地理解,这里是基本的循环解决方案:

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
            }
        }
    }

我尝试了array_uintersection,如下所示:

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

但是它给了我未定义的索引'id'.我检查了以下问题:比较具有不同键名的两个数组.这个问题的第一个答案给出了一个我想避免的循环解决方案.第二个答案建议更改SQL结构,但我对此无能为力.所以,

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?

推荐答案

使用array_uintersect_uassoc函数的解决方案:

$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);

输出:

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

根据您的情况:通过第一个数组的[ id ]和第二个数组的[ cid ]交叉这两个数组 ,我们应该只为那些键['id', 'cid']考虑一个键比较功能.
在每个比较步骤上都有所需的键后,只需要比较它们的值即可(使用值比较功能)

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

演示链接

这篇关于相交(内部联接)具有不同键名的两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆