8

我已经尝试了好几个小时了。

我有两个多维数组

    $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
)

)

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

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

任何帮助都是极好的

4

3 回答 3

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;事后做。

于 2013-04-21T19:55:07.213 回答
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.

于 2013-04-21T19:56:12.053 回答
0

用这个怎么样?通过修改thelamborghinistory 的答案,

如果有重复,请取消设置动态键。

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
于 2016-10-21T06:41:27.500 回答