比较两个多维数组,然后只创建独特的阵 [英] Compare two multidimensional arrays then create array of only unique

查看:97
本文介绍了比较两个多维数组,然后只创建独特的阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力,现在得到这个好几个小时。

I've been trying to get this for hours now.

我有两个多维数组

    $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抢只有新的数据是第一公共阵列之前。

I need to compare $newData and $oldData and grab only the new data that is before the first common array.

我的$ newData将为:

My $newData will then be:

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

我试过一切从array_unique,如果比较ID按键,但没有正常工作。

I've tried everything from array_unique, if comparing the ID keys but nothing is working properly.

我是否需要将它们合并,第一?地图呢? Bahh,我不知道,我很失落。

Do I need to merge them, first? map them? Bahh, I have no idea, I am so lost.

任何帮助将是真棒

推荐答案

我只想做一个嵌套的foreach循环。我不知道你使用的编程语言,但假设它的PHP($):

I would just do a nested foreach loop. I don't know which programming language You're using, but assuming that it's 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; 之后

You then have the desired array in the $tmpArray variable. You can make of course $newData = $tmpArray; afterwards.

这篇关于比较两个多维数组,然后只创建独特的阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆