Remove duplicated elements of associative array in PHP

后端 未结 2 1116
刺人心
刺人心 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条回答
  •  独厮守ぢ
    2020-12-05 02:46

    Regardless what others are offering here, you are looking for a function called array_uniqueDocs. The important thing here is to set the second parameter to SORT_REGULAR and then the job is easy:

    array_unique($result, SORT_REGULAR);
    

    The meaning of the SORT_REGULAR flag is:

    compare items normally (don't change types)

    And that is what you want. You want to compare arraysDocs here and do not change their type to string (which would have been the default if the parameter is not set).

    array_unique does a strict comparison (=== in PHP), for arrays this means:

    $a === $b TRUE if $a and $b have the same key/value pairs in the same order and of the same types.

    Output (Demo):

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

提交回复
热议问题