I have multiple associative arrays, similar to the following:
$arr1 = array(0 => 12, 5 => 10, 19 => 48);
$arr2 = array(0 => 14, 7 => 9, 12 => 11, 19 => 30);
I would like to merge these arrays so that I have a single set of keys (0, 5, 7, 12, 19) and each points to an array with the values from the original arrays, and null
if the value doesn't exist in the original array:
$merge = array(
0 => array(12, 14),
5 => array(10, null),
7 => array(null, 9),
12 => array(null, 11),
19 => array(48, 30)
);
I need to be able to do this for an arbitrary number of arrays. I'm not sure where to start with this.
I could, I suppose, iterate through each array, append it's value to the result - but I'd have to check to see if I have the requisite number of elements in each resulting array before appending the current value to that index - which isn't terribly efficient.
$arr1 = array(0 => 12, 5 => 10, 19 => 48);
$arr2 = array(0 => 14, 7 => 9, 12 => 11, 19 => 30);
$keys = array_merge(array_keys($arr1), array_keys($arr2));
$merged = array();
foreach ($keys as $key) {
$merged[$key] = array();
$merged[$key][] = isset($arr1[$key]) ? $arr1[$key] : null;
$merged[$key][] = isset($arr2[$key]) ? $arr2[$key] : null;
}
ksort($merged);
echo '<pre>', var_dump($merged), '</pre>';
modified for an arbitrary number of arrays
$arrays = array(
array(0 => 12, 5 => 10, 19 => 48),
array(0 => 14, 7 => 9, 12 => 11, 19 => 30),
// ... more arrays
);
$keys = array();
foreach ($arrays as $arr) {
$keys = array_merge($keys, array_keys($arr));
}
$merged = array();
foreach ($keys as $key) {
$merged[$key] = array();
foreach ($arrays as $arr) {
$merged[$key][] = isset($arr[$key]) ? $arr[$key] : null;
}
}
ksort($merged);
echo '<pre>', var_dump($merged), '</pre>';