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

时间:2022-08-10 21:34:37

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.

我正在寻找一种在多维数组之间进行非常奇怪的数组合并的方法。以下面两个数组arrayOne和arrayTwo为例。

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. 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中,如果数字和字母组合都是唯一的,它将显示唯一的数组项。它会将一个数组中的值与另一个数组合并,如果该值不存在,那么它将提供一个空字符串。 (请参阅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' => '')
    );

1 个解决方案

#1


3  

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

#1


3  

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