比较两个多维数组然后创建唯一的数组

时间:2013-04-21 19:31:13

标签: php arrays multidimensional-array unique

我一直在试着这几个小时。

我有两个多维数组

    $newData (
    [0] => Array(
        [id] => 1
        [name] => John
        [sex] => male
    )
    [1] => Array(
        [id] => 2
        [name] => Kenny
        [sex] => male
    )
    [2] => Array(
        [id] => 3
        [name] => Sarah
        [sex] => female
    )
    [3] => Array(
        [id] => 4
        [name] => George
        [sex] => male
    )
)

$oldData (
    [0] => Array(
        [id] => 3
        [name] => Sarah
        [sex] => female
    )
    [1] => Array(
        [id] => 4
        [name] => George
        [sex] => male
    )
    [2] => Array(
        [id] => 5
        [name] => Peter
        [sex] => male
    )
    [3] => Array(
        [id] => 6
        [name] => Lexi
        [sex] => female
    )
)

我需要比较$ newData和$ oldData,并且只获取第一个公共数组之前的新数据。

我的$ newData将是:

$newData (
[0] => Array(
    [id] => 1
    [name] => John
    [sex] => male
)
[1] => Array(
    [id] => 2
    [name] => Kenny
    [sex] => male
)

我已尝试过array_unique中的所有内容,如果比较ID键但没有任何工作正常。

我需要首先合并它们吗?映射他们?呸,我不知道,我迷失了。

任何帮助都很棒

3 个答案:

答案 0 :(得分:7)

我会做一个嵌套的foreach循环。我不知道你正在使用哪种编程语言,但假设它是PHP($):

$tmpArray = array();

foreach($newData as $data1) {

  $duplicate = false;
  foreach($oldData as $data2) {
    if($data1['id'] === $data2['id'] && $data1['name'] === $data2['name'] && $data1['sex'] === $data2['sex']) $duplicate = true;
  }

  if($duplicate === false) $tmpArray[] = $data1;
}

然后,您在$tmpArray变量中拥有所需的数组。你可以事后$newData = $tmpArray;

答案 1 :(得分:1)

只需迭代$newData,直到找到$oldData的第一个元素?

$cmp = $oldData[0];
$data = array();
foreach ($newData as $el) {
    if ($el['id'] === $cmp['id']
      && $el['name'] === $cmp['name']
      && $el['sex'] === $cmp['sex'])
        break;
    $data[] = $el;
}

您的新数据将存储在$data

答案 2 :(得分:0)

如何使用它?通过修改thelamborghinistory's回答,

如果存在重复,请取消设置动态密钥。

public function removeDuplicate($oldData, $newData, $key)
{
    $tmpArray = array();
    foreach ($newData as $data1) {
        $duplicate = false;
        foreach ($oldData as $data2k => $data2v) {
            if ($data1[$key] === $data2v[$key]) {
                unset($newData[$data2k]);
                $duplicate = true;
            }
        }
        if ($duplicate === true) {
            $tmpArray[] = $data1;
        } else {
            $tmpArray[] = $data1;
        }
    }
    return $tmpArray;
}

然后你必须打电话,

removeDuplicate($oldData, $newData, 'name');//or whatever you want