Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

Remove duplicated elements of associative array in PHP

$result = array(
    0=>array('a'=>1,'b'=>'Hello'),
    1=>array('a'=>1,'b'=>'other'),
    2=>array('a'=>1,'b'=>'other'),
);

If it is duplicated removed it, so the result is as follows:

$result = array(
    0=>array('a'=>1,'b'=>'Hello'),
    1=>array('a'=>1,'b'=>'other')   
);

Could any know to do this?

Thanks

question from:https://stackoverflow.com/questions/13857775/remove-duplicated-elements-of-associative-array-in-php

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...