array_unique for arrays inside array

浪尽此生 提交于 2019-12-01 13:51:10

问题


I need a function like array_unique for arrays inside array.

The Case - should be equal, but output "not equal":

<?php
$arr=array(array('a',1),array('a',2));
$arr2=array_unique($arr);
if($arr2==$arr){
  echo "equal";
}
else{
  echo "not equal";
}
?>

How should the code be changed to get output "equal"?


回答1:


You should modify your call for array_unique to have it include the SORT_REGULAR flag.

$arr2 = array_unique($arr, SORT_REGULAR);



回答2:


If you want to test if the outer array has unique entries, then stringify the inner contents first for a comparison:

$arr1 = array_map("serialize", $arr);
$arr2 = array_unique($arr1);
if ($arr2 == $arr1) {



回答3:


function array_unique_when_values_are_serializable($main_array) {
    return array_map('unserialize', array_values(array_unique(array_map('serialize', $main_array))));
}


来源:https://stackoverflow.com/questions/5211900/array-unique-for-arrays-inside-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!