我有多个关联数组,类似于以下内容:
$arr1 = array(0 => 12, 5 => 10, 19 => 48);
$arr2 = array(0 => 14, 7 => 9, 12 => 11, 19 => 30);
我想合并这些数组,以便我有一组键(0,5,7,12,19),每个键都指向一个包含原始数组值的数组,null
如果原始数组中不存在该值:
$merge = array(
0 => array(12, 14),
5 => array(10, null),
7 => array(null, 9),
12 => array(null, 11),
19 => array(48, 30)
);
我需要能够为任意数量的数组执行此操作。我不知道从哪里开始。
我想,我可以迭代遍历每个数组,将它的值附加到结果上 - 但是我必须在将当前值附加到该索引之前检查每个结果数组中是否有必要数量的元素 - 这不是非常有效。
想法或指示?
答案 0 :(得分:1)
修改
<?php
$arr1 = array(0 => 12, 5 => 10, 19 => 48);
$arr2 = array(0 => 14, 7 => 9, 12 => 11, 19 => 30);
foreach($arr1 as $k => $v){
if(array_key_exists($k, $arr2)){
$newarr[$k][] = $v;
$newarr[$k][] = $arr2[$k];
}else{
$newarr[$k][] = $v;
$newarr[$k][] = 'NULL';
}
}
foreach($arr2 as $k => $v){
if(!array_key_exists($k, $arr1)){
$newarr[$k][] = 'NULL';
$newarr[$k][] = $v;
}
}
ksort($newarr);
echo '<pre>';
print_r($newarr);
?>
输出:
Array
(
[0] => Array
(
[0] => 12
[1] => 14
)
[5] => Array
(
[0] => 10
[1] => NULL
)
[7] => Array
(
[0] => NULL
[1] => 9
)
[12] => Array
(
[0] => NULL
[1] => 11
)
[19] => Array
(
[0] => 48
[1] => 30
)
)
答案 1 :(得分:1)
我认为这就是你要找的东西。
/*Merge function*/
function merge($a1, $a2)
{
foreach($a1 as $key => $val)
$a1[$key] = Array($a1[$key], null);
foreach($a2 as $key => $val)
$a1[$key] = Array((isset($a1[$key]))? $a1[$key][0]: null, $val);
return ksort($a1);
}
/*Test*/
$arr1 = array(0 => 12, 5 => 10, 19 => 48);
$arr2 = array(0 => 14, 7 => 9, 12 => 11, 19 => 30);
foreach(merge($arr1, $arr2) as $key => $val){
echo "<br />$key --";
print_r($val);
}
/*output*/
0 --Array ( [0] => 12 [1] => 14 )
5 --Array ( [0] => 10 [1] => )
7 --Array ( [0] => [1] => 9 )
12 --Array ( [0] => [1] => 11 )
19 --Array ( [0] => 48 [1] => 30 )
答案 2 :(得分:1)
$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>';
针对任意数量的数组进行了修改
$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>';
答案 3 :(得分:0)
尝试此功能:
function multimerge ($array1, $array2) {
if (is_array($array2) && count($array2)) {
foreach ($array2 as $k => $v) {
if (is_array($v) && count($v)) {
$array1[$k] = multimerge($array1[$k], $v);
} else {
$array1[$k] = $v;
}
}
} else {
$array1 = $array2;
}
return $array1;
}