从PHP中的多维数组中删除重复项

时间:2018-02-24 09:13:26

标签: php arrays

我现在想如何从多维数组中删除重复项。我有一个看起来像这样的数组:

之前的数组

Array
(
    [0] => Array
    (
        [0] => 'Hello'
        [1] => 'Test'
    )

    [1] => Array
    (
        [0] => 'Friend'
        [1] => 'Test'
    )

    [2] => Array
    (
        [0] => 'Hello'
        [1] => 'Code'
    )

    [3] => Array
    (
        [0] => 'Hello'
        [1] => 'Test'
    )

    [4] => Array
    (
        [0] => 'hello'
        [1] => 'Test'
    )

    [5] => Array
    (
        [0] => 'Hello'
        [1] => 'Test'
    )
)

我希望它看起来像这样:

之后的数组
Array
(
    [0] => Array
    (
        [0] => 'Hello'
        [1] => 'Test'
    )

    [1] => Array
    (
        [0] => 'Friend'
        [1] => 'Test'
    )

    [2] => Array
    (
        [0] => 'Hello'
        [1] => 'Code'
    )

    [3] => Array
    (
        [0] => 'hello'
        [1] => 'Test'
    )
)

如您所见,第三个和第五个元素被删除,因为元素零与它们相同。解决这个问题最有效的方法是什么?谢谢。

1 个答案:

答案 0 :(得分:4)

您可以使用array_unique

Php output demo

$arrays = [
    [
        "Hello",
        "Test"
    ],
    [
        "Friend",
        "Test"
    ],
    [
        "Hello",
        "Test"
    ],
    [
        "hello",
        "Test"
    ]
];

var_dump(array_unique($arrays, SORT_REGULAR));

那会给你:

array(3) {
  [0]=>
  array(2) {
    [0]=>
    string(5) "Hello"
    [1]=>
    string(4) "Test"
  }
  [1]=>
  array(2) {
    [0]=>
    string(6) "Friend"
    [1]=>
    string(4) "Test"
  }
  [3]=>
  array(2) {
    [0]=>
    string(5) "hello"
    [1]=>
    string(4) "Test"
  }
}