基于spefic密钥PHP合并数组

时间:2015-06-30 04:53:20

标签: php arrays merge

Array
(
    [0] => Array
        (
            [employee] => 15
            [first_name] => Person1
            [surname] => Person1
            [totaltime] => 183.75
            [FirstValue] => 1
        )

[1] => Array
    (
        [employee] => 15
        [first_name] => Person1
        [surname] => Person1
        [totaltime] => 183.75
        [SecondValue] => 2            
    )
)

我想要这样的输出

Array
(
    [0] => Array
        (
            [employee] => 15
            [first_name] => Person1
            [surname] => Person1
            [totaltime] => 183.75
            [FirstValue] => 1
            [SecondValue] => 2
        )
)

我有一个多维数组。每个元素都有一个员工作为密钥,可以是相同的也可以是不同的。我想将数组与相同的EmployeeID合并。另外2名员工可能有不同的元素,如FirstValueSecondValue等。我想合并我在上面输出中显示的唯一元素。

4 个答案:

答案 0 :(得分:0)

$output = array_merge($array1, $array2);

查看array_merge().

答案 1 :(得分:0)

使用此:

$data = array(); // your data

array_merge($data[0],$data[1]); //merge it to first data
unset($data[1]); // and unset the second data with 
echo '<pre>';
print_r($data);
echo '<pre>';

答案 2 :(得分:0)

$arr = Array(
   Array
        (
            employee => 15,
            first_name => 'Person1',
           surname => 'Person1',
            totaltime => 183.75,
            FirstValue => 1
        ),
 Array
    (
        employee=> 15,
        first_name => Person1,
        surname=> Person1,
        totaltime => 183.75,
        SecondValue => 2            
    ),
       Array
        (
            employee => 16,
            first_name => 'Person1',
           surname => 'Person1',
            totaltime => 183.75,
            FirstValue => 1
        ));

$ids = array();                            // array employee => key

foreach($arr as $key => &$item)
   if(isset($ids[$item['employee']])) {    // is there such employee in ids
      $arr[$ids[$item['employee']]] =      // yes - add values from current item
          array_replace($arr[$ids[$item['employee']]], $item);  
      unset($arr[$key]);                   // and remove it from array
   }
   else $ids[$item['employee']] = $key;    // save current key

print_r($arr);

结果

Array
(
    [0] => Array
        (
            [employee] => 15
            [first_name] => Person1
            [surname] => Person1
            [totaltime] => 183.75
            [FirstValue] => 1
            [SecondValue] => 2
        )

    [2] => Array
        (
            [employee] => 16
            [first_name] => Person1
            [surname] => Person1
            [totaltime] => 183.75
            [FirstValue] => 1
        )

)

答案 3 :(得分:0)

$result = [];
foreach ($array as $employee) {
    if (isset($result[$employee['employee']])) {
        $result[$employee['employee']] += $employee;
    } else {
        $result[$employee['employee']] = $employee;
    }
}

使用数组键是唯一的(在$result中)进行重复数据删除和合并值的事实。