我有一个像这样的数组
Array (
[0] => Array (
[0] => 1519
[1] => 6
[2] =>
[3] =>
)
[1] => Array (
[0] => 26
[1] => 3
[2] =>
[3] =>
)
[3] => Array (
[0] => 1059
[1] => 3
[2] =>
[3] =>
)
[4] => Array (
[0] => 26
[1] =>
[2] => 2
[3] =>
)
[5] => Array (
[0] => 39
[1] =>
[2] => 2
[3] =>
)
[6] => Array (
[0] => 1502
[1] =>
[2] => 2
[3] =>
)
[7] => Array (
[0] => 1059
[1] =>
[2] => 2
[3] =>
)
[8] => Array (
[0] => 966
[1] =>
[2] => 2
[3] =>
)
[9] => Array (
[0] => 1519
[1] =>
[2] =>
[3] => 1
)
[10] => Array (
[0] => 1502
[1] =>
[2] =>
[3] => 4
)
[11] => Array (
[0] => 1059
[1] =>
[2] =>
[3] => 5
)
[12] => Array (
[0] => 966
[1] =>
[2] =>
[3] => 3
)
[13] => Array (
[0] => 631
[1] =>
[2] =>
[3] => 6
)
)
我想要这样
Array (
[0] => Array (
[0] => 1519
[1] => 6
[2] =>
[3] => 1
)
[1] => Array (
[0] => 26
[1] => 3
[2] => 2
[3] =>
)
[2] => Array (
[0] => 1059
[1] => 3
[2] => 2
[3] => 5
)
[3] => Array (
[0] => 39
[1] =>
[2] => 2
[3] =>
)
[4] => Array (
[0] => 1502
[1] =>
[2] => 2
[3] => 4
)
[5] => Array (
[0] => 966
[1] =>
[2] => 2
[3] => 3
)
[6] => Array (
[0] => 631
[1] =>
[2] =>
[3] => 6
)
)
我尝试做的是合并主键的重复项,每个记录的第一个索引,并获取数组中的第一个非空值。
传入的数据有14个元素,合并后将有7个元素。
例如
[0] => Array (
[0] => 1519
[1] => 6
[2] =>
[3] =>
)
与
匹配[9] => Array (
[0] => 1519
[1] =>
[2] =>
[3] => 1
)
并成为:
[0] => Array (
[0] => 1519
[1] => 6
[2] =>
[3] => 1
)
抓取记录剩余索引的第一个非空值。
答案 0 :(得分:0)
我会先通过主键分组来处理这个问题,这样你就可以将要互相合并的数组(在这种情况下只有两个)作为数组的唯一元素。然后创建另一个阵列" out"从每个主键的第一个匹配开始,然后在循环中一次一个地遍历该主键的剩余字段。其中NULL,使用最新记录。如果由于某种原因,您有3条具有相同主键的记录,则此过程可以继续,直到您具有非空值的NULL值:
<?php
// this is the inputted data
$ar = Array (
0 => Array (
0 => 1519,
1 => 6,
2 => NULL,
3 => NULL,
) ,
1 => Array (
0 => 26 ,
1 => 3 ,
2 => NULL,
3 => NULL,
) ,
3 => Array (
0 => 1059 ,
1 => 3 ,
2 => NULL,
3 => NULL,
) ,
4 => Array (
0 => 26 ,
1 => NULL,
2 => 2 ,
3 => NULL,
) ,
5 => Array (
0 => 39 ,
1 => NULL,
2 => 2 ,
3 => NULL,
) ,
6 => Array (
0 => 1502 ,
1 => NULL,
2 => 2 ,
3 => NULL,
) ,
7 => Array (
0 => 1059 ,
1 => NULL,
2 => 2 ,
3 => NULL,
) ,
8 => Array (
0 => 966 ,
1 => NULL,
2 => 2 ,
3 => NULL,
) ,
9 => Array (
0 => 1519 ,
1 => NULL,
2 => NULL,
3 => 1 ,
) ,
10 => Array (
0 => 1502 ,
1 => NULL,
2 => NULL,
3 => 4 ,
) ,
11 => Array (
0 => 1059 ,
1 => NULL,
2 => NULL,
3 => 5 ,
) ,
12 => Array (
0 => 966 ,
1 => NULL,
2 => NULL,
3 => 3 ,
) ,
13 => Array (
0 => 631 ,
1 => NULL,
2 => NULL,
3 => 6 ,
),
);
// Group by primary key so we can see what arrays are being merged
$toMerge = [];
foreach($ar as $a)
{
if(!isset($toMerge[$a[0]])){$toMerge[$a[0]] = [];}
$toMerge[$a[0]][] = $a;
}
// use the first non-NULL column for each column by primary key
$out = [];
foreach($toMerge as $items)
{
$cols = $items[0];
foreach($items as $item)
{
foreach($item as $k=>$v)
{
if( !isset($cols[$k]) )
{
$cols[$k] = $v;
}
}
}
$out[] = $cols;
}
// this is our output
print_r($out);