PHP比较2个多维数组并根据键值删除重复数据

时间:2013-02-23 11:40:02

标签: php arrays multidimensional-array

我有2个阵列,例如

OldMembers:

Array (
  [0] => Array
    (
        [time] => 1361612421
        [memberid] => 90
    )

  [1] => Array
    (
        [time] => 1361614422
        [memberid] => 96
    )

  [2] => Array
    (
        [time] => 1361617423
        [memberid] => 108
    )
)

和NewMembers

Array (
  [0] => Array
    (
        [time] => 1361618411
        [memberid] => 103
    )

  [1] => Array
    (
        [time] => 1361618443
        [memberid] => 129
    )
  [2] => Array
    (
        [time] => 1361618463
        [memberid] => 96
    )
)

根据关键memberid从NewMembers中删除重复项的最佳方法是什么?例如。在这种情况下,我需要从NewMembers中删除第二个数组,因为memberid 96已经存在于位置1的OldMembers中......我只需要从NewMembers数组中删除该实例?

2 个答案:

答案 0 :(得分:3)

肯定不是最好的答案,但如果没有其他人会提出任何建议,至少你会有这个。

foreach($newmembers as $newmemberId => $newmember) {
    foreach($oldmembers as $oldmember) {
        if($oldmember['memberid'] == $newmember['memberid']) {
            unset($newmembers[$newmemberId]);
            break;
        }
    }
}

$ newmembers和$ oldmembers当然是你的阵列。

答案 1 :(得分:1)

尝试

array_unique( array_merge($oldMember, $newMember) );

未经测试但希望它能够正常工作。

经过测试的代码。

<?php
$oldMember = array
(
    '0' => array
    (
        'time' => 1361612421,
        'memberid' => 90
    ),
    '1' => array
    (
        'time' => 1361614422,
        'memberid' => 96
    ),
    '2' => array
    (
        'time' => 1361617423,
        'memberid' => 108
    )
);

$newMember = array
(
    '0' => array
    (
        'time' => 1361618411,
        'memberid' => 103
    ),
    '1' => array
    (
        'time' => 1361618443,
        'memberid' => 129
    ),
    '2' => array
    (
        'time' => 1361618463,
        'memberid' => 96
    )
);


$id_arr = array();
$final_arr = array();

checkmemberidArray($oldMember, $id_arr, $final_arr);
checkmemberidArray($newMember, $id_arr, $final_arr);

function checkmemberidArray($arr, &$id_arr, &$final_arr)
{
    foreach ($arr as $key => $value)
    {
        if (!in_array($value['memberid'], $id_arr))
        {
            $id_arr[] = $value['memberid'];
            $final_arr[] = $value;
        }
    }
}

echo "<pre>";
print_r($final_arr);
echo "</pre>";
?>