PHP排除合并多维数组的重复

时间:2015-11-12 21:11:00

标签: php arrays multidimensional-array merge

我想合并两个多维数组。考虑下面的场景。我有两个我想合并的数组。但是,我想删除/避免合并任何可以识别的重复记录,因为他们共享' documentId'。

数组#1

Array 
(
    [0] => Array
        (
            ['documentId'] => 124   
            ['name'] => "Title #1"
            ['version'] => "1"
        )
    [1] => Array
        (
            ['documentId'] => 123   
            ['name'] => "Title #2"
            ['version'] => "1"
        )
)

数组#2

Array
(
    [0] => Array
        (
            ['documentId'] => 123   
            ['name'] => "Title #2 updated"
            ['version'] => "2"
        )
)

新数组/合并数组

Array

    Array 
    (
        [0] => Array
            (
                ['documentId'] => 123   
                ['name'] => "Title #2 updated"
                ['version'] => "2"
            )
        [1] => Array
            (
                ['documentId'] => 124   
                ['name'] => "Title #2"
                ['version'] => "1"
            )
    )

我查看了array_replace_recursive()函数。我无法使用它,因为它需要专门比较属性' documentId'而不是数组的关键。

4 个答案:

答案 0 :(得分:0)

只需循环遍历数组并将其设置为另一个数组,文档ID为关键字。以后的值会覆盖之前设置的值。

示例:

$merged = array();
foreach($array1 as $value){
    $merged[$value['documentId']] = $value;
}

foreach($array2 as $value){
    $merged[$value['documentId']] = $value;
}

答案 1 :(得分:0)

合并$ arr1和$ arr2

时,将documentId设置为键
$new_array = array();
foreach ( $arr1 as $v ) {
    $new_array[ $v['documentID'] ] = $v;
}
foreach ( $arr2 as $v ) {
    $new_array[ $v['documentID'] ] = $v;
}

答案 2 :(得分:0)

array_column()可以使用documentID重新编制索引,以便array_replace()替换$array1中具有相同键的$array2元素:

$result = array_replace(array_column($array1, null, 'documentId'),
                        array_column($array2, null, 'documentId'));

然后如果需要重新索引:

$result = array_values($result)

答案 3 :(得分:0)

循环两个数组,如果需要,可以合并或替换值

<?php

$students1 = array(
    0 => array(
        'student_id' => 1,
        'name' => 'John',
        'enrollment' => 'AAA111'
    ),
    1 => array(
        'student_id' => 2,
        'name' => 'Mike',
        'enrollment' => 'BBB222'
    )
);

$students2 = array(
    0 => array(
        'student_id' => 1,
        'name' => 'John',
        'enrollment' => 'AAA111'
    ),
    1 => array(
        'student_id' => 3,
        'name' => 'Anton',
        'enrollment' => 'BBB333'
    )
);

$students = [];

foreach ($students1 as $student) {
    $students[$student['student_id']] = $student;
}

foreach ($students2 as $student) {
    if (!isset($students[$student['student_id']])) {
        $students[$student['student_id']] = $student;
    }
}


var_dump(array_values($students));