PHP得到一个多维数组的独特价值 [英] php getting unique values of a multidimensional array

查看:182
本文介绍了PHP得到一个多维数组的独特价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
   PHP多维数组删除重复

我有一个这样的数组:

$a = array ( 
    0 => array ( 'value' => 'America', ), 
    1 => array ( 'value' => 'England', ),  
    2 => array ( 'value' => 'Australia', ), 
    3 => array ( 'value' => 'America', ), 
    4 => array ( 'value' => 'England', ), 
    5 => array ( 'value' => 'Canada', ), 
)

我怎样才能删除重复值,使我得到这样的:

How can I remove the duplicate values so that I get this:

$a = array ( 
    0 => array ( 'value' => 'America', ), 
    1 => array ( 'value' => 'England', ),  
    2 => array ( 'value' => 'Australia', ), 
    4 => array ( 'value' => 'Canada', ), 
)

我试着用array_unique,但这并不因为这个数组是一个多维的工作,我想。

I tried using array_unique, but that doesn't work due to this array being multidimensional, I think.

编辑:我也需要这个数组是多维的,在这种形式,我不能将其压平

I also need this array to be multi-dimensional and in this format, I can't flatten it.

感谢。

谢谢!

推荐答案

array_unique 使用比较值之前串转换,找到独特的价值观:

array_unique is using string conversion before comparing the values to find the unique values:

注意:有两个因素被认为是平等的,当且仅当(字符串)$ elem1 ===(字符串)$ elem2时。在话:当字符串重新presentation是一样的。第一元件将被使用。

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.

但是,一个阵列总是会转换为阵列

But an array will always convert to Array:

var_dump("Array" === (string) array());

您可以通过指定解决这个问题的的 SORT_REGULAR 的中的第二个参数模式 array_unique

You can solve this by specifying the SORT_REGULAR mode in the second parameter of array_unique:

$unique = array_unique($a, SORT_REGULAR);

或者,如果不工作,由之前序列化阵列和的反序列化该调用后 array_unique 来找到的唯一值:

Or, if that doesn’t work, by serializing the arrays before and unserializing it after calling array_unique to find the unique values:

$unique = array_map('unserialize', array_unique(array_map('serialize', $a)));

这篇关于PHP得到一个多维数组的独特价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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