如何在数组数组上使用 array_unique? [英] How do I use array_unique on an array of arrays?

查看:25
本文介绍了如何在数组数组上使用 array_unique?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组

Array(
[0] => Array
    (
        [0] => 33
        [user_id] => 33
        [1] => 3
        [frame_id] => 3
    )

[1] => Array
    (
        [0] => 33
        [user_id] => 33
        [1] => 3
        [frame_id] => 3
    )

[2] => Array
    (
        [0] => 33
        [user_id] => 33
        [1] => 8
        [frame_id] => 8
    )

[3] => Array
    (
        [0] => 33
        [user_id] => 33
        [1] => 3
        [frame_id] => 3
    )

[4] => Array
    (
        [0] => 33
        [user_id] => 33
        [1] => 3
        [frame_id] => 3
    )

)

正如你所看到的,key 0 与 1、3 和 4 相同.key 2 与它们不同.

As you can see key 0 is the same as 1, 3 and 4. And key 2 is different from them all.

对它们运行 array_unique 函数时,只剩下

When running the array_unique function on them, the only left is

Array (
[0] => Array
    (
        [0] => 33
        [user_id] => 33
        [1] => 3
        [frame_id] => 3
    )
)

知道为什么 array_unique 没有按预期工作吗?

Any ideas why array_unique isn't working as expected?

推荐答案

这是因为 array_unique 使用字符串比较来比较项目.来自文档:

It's because array_unique compares items using a string comparison. From the docs:

注意:考虑两个元素相等当且仅当 (string) $elem1===(字符串)$elem2.换句话说:当字符串表示相同时.将使用第一个元素.

Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. The first element will be used.

数组的字符串表示只是单词Array,不管它的内容是什么.

The string representation of an array is simply the word Array, no matter what its contents are.

您可以使用以下方法做您想做的事:

You can do what you want to do by using the following:

$arr = array(
    array('user_id' => 33, 'frame_id' => 3),
    array('user_id' => 33, 'frame_id' => 3),
    array('user_id' => 33, 'frame_id' => 8)
);

$arr = array_intersect_key($arr, array_unique(array_map('serialize', $arr)));

//result:
array
  0 => 
    array
      'user_id' => int 33
      'user' => int 3
  2 => 
    array
      'user_id' => int 33
      'user' => int 8

这是它的工作原理:

  1. 每个数组项都被序列化.这个将是唯一的基于数组的内容.

  1. Each array item is serialized. This will be unique based on the array's contents.

这个结果通过array_unique运行,所以只有具有唯一性的数组留下签名.

The results of this are run through array_unique, so only arrays with unique signatures are left.

array_intersect_key 将需要独特项目的键来自映射/唯一函数(因为保留了源数组的键)并拉它们来自您的原始来源数组.

array_intersect_key will take the keys of the unique items from the map/unique function (since the source array's keys are preserved) and pull them out of your original source array.

这篇关于如何在数组数组上使用 array_unique?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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