1

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.

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)

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 Answer 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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.