问题
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:
$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);
来源:https://stackoverflow.com/questions/7670062/merge-php-array-based-on-two-unique-values