简体   繁体   English

基于两个唯一值合并php数组

[英]Merge php array based on two unique values

I'm looking for a way to do a pretty odd array merge between multidimensional arrays. 我正在寻找一种在多维数组之间进行非常奇特的数组合并的方法。 Take the following two arrays arrayOne and arrayTwo as examples. 以以下两个数组arrayOnearrayTwo为例。

I'd like to merge the arrays into arrayThree , which will show arrays items that are unique if both number and letter combined are unique. 我想合并数组到arrayThree ,它会显示阵列项目如果两个是唯一numberletter组合是唯一的。 It'll merge the values from one array with another and if the value isn't present, then it'll provide an empty string. 它将合并一个数组中的值与另一个数组中的值,如果不存在该值,则它将提供一个空字符串。 (see arrayThree for what I mean) (请参阅arrayThree我的意思)

Any ideas? 有任何想法吗?

$arrayOne = array(
        array('number' => 1, 'letter' => 'a', 'qcol' => 'tennis'),
        array('number' => 1, 'letter' => 'b', 'qcol' => 'soccer'),
        array('number' => 2, 'letter' => 'a', 'qcol' => 'basketball'),
        array('number' => 2, 'letter' => 'b', 'qcol' => 'football'),
        array('number' => 3, 'letter' => 'a', 'qcol' => 'bowling'),
        array('number' => 3, 'letter' => 'b', 'qcol' => 'rugby')
    );

$arrayTwo = array(
        array('number' => 1, 'letter' => 'a', 'rval' => 'bus'),
        array('number' => 1, 'letter' => 'b', 'rval' => 'car'),
        array('number' => 2, 'letter' => 'a', 'rval' => 'truck'),
        array('number' => 2, 'letter' => 'b', 'rval' => 'plane'),
        array('number' => 4, 'letter' => 'b', 'rval' => 'boat')
    );

would merge into: 将合并为:

$arrayThree = array(
        array('number' => 1, 'letter' => 'a', 'rval' => 'bus', 'qcol' => 'tennis'),
        array('number' => 1, 'letter' => 'b', 'rval' => 'car', 'qcol' => 'soccer'),
        array('number' => 2, 'letter' => 'a', 'rval' => 'truck', 'qcol' => 'basketball'),
        array('number' => 2, 'letter' => 'b', 'rval' => 'plane', 'qcol' => 'football'),
        array('number' => 3, 'letter' => 'a', 'rval' => '', 'qcol' => 'bowling'),
        array('number' => 3, 'letter' => 'b', 'rval' => '', 'qcol' => 'rugby'),
        array('number' => 4, 'letter' => 'b', 'rval' => 'boat', 'qcol' => '')
    );
$arrayThree = array();

foreach ($arrayOne as $i) {
    $arrayThree[$i['number'] . $i['letter']] = $i + array('rval' => null);
}
foreach ($arrayTwo as $i) {
    $key = $i['number'] . $i['letter'];
    if (isset($arrayThree[$key])) {
        $arrayThree[$key]['rval'] = $i['rval'];
    } else {
        $arrayThree[$key] = $i + array('qcol' => null);
    }
}

$arrayThree = array_values($arrayThree);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM