Remove duplicated elements of associative array in PHP

后端 未结 2 1118
刺人心
刺人心 2020-12-05 02:26
$result = array(
    0=>array(\'a\'=>1,\'b\'=>\'Hello\'),
    1=>array(\'a\'=>1,\'b\'=>\'other\'),
    2=>array(\'a\'=>1,\'b\'=>\'other\')         


        
2条回答
  •  Happy的楠姐
    2020-12-05 02:41

    First things first, you can not use plain array_unique for this problem because array_unique internally treats the array items as strings, which is why "Cannot convert Array to String" notices will appear when using array_unique for this.

    So try this:

    $result = array(
        0=>array('a'=>1,'b'=>'Hello'),
        1=>array('a'=>1,'b'=>'other'),
        2=>array('a'=>1,'b'=>'other')
    );
    
    $unique = array_map("unserialize", array_unique(array_map("serialize", $result)));
    
    print_r($unique);
    

    Result:

    Array
    (
        [0] => Array
            (
                [a] => 1
                [b] => Hello
            )
    
        [1] => Array
            (
                [a] => 1
                [b] => other
            )
    
    )
    

    Serialization is very handy for such problems.

    If you feel that's too much magic for you, check out this blog post

    function array_multi_unique($multiArray){
    
      $uniqueArray = array();
    
      foreach($multiArray as $subArray){
    
        if(!in_array($subArray, $uniqueArray)){
          $uniqueArray[] = $subArray;
        }
      }
      return $uniqueArray;
    }
    
    $unique = array_multi_unique($result);
    
    print_r($unique);
    

    Ironically, in_array is working for arrays, where array_unique does not.

提交回复
热议问题