dongluo6343 2010-03-14 13:14
浏览 50
已采纳

php获取多维数组的唯一值[重复]

Possible Duplicate:
php multi-dimensional array remove duplicate

I have an array like this:

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

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

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

  • 写回答

3条回答 默认 最新

  • douqing0713 2010-03-14 13:37
    关注

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

    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());
    

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

    $unique = array_unique($a, SORT_REGULAR);
    

    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)));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大