How to remove all instances of duplicated values from an array

前端 未结 9 1088
心在旅途
心在旅途 2021-01-02 19:48

I know there is array_unique function, but I want to remove duplicates. Is there a built-in function or do I have to roll my own.

Example input:

相关标签:
9条回答
  • 2021-01-02 20:21

    If you want to only leave values in the array that are already unique, rather than select one unique instance of each value, you will indeed have to roll your own. Built in functionality is just there to sanitise value sets, rather than filter.

    0 讨论(0)
  • 2021-01-02 20:24

    The answer on top looks great, but on a side note: if you ever want to eliminate duplicates but leave the first one, using array_flip twice would be a pretty simple way to do so. array_flip(array_flip(x))

    0 讨论(0)
  • 2021-01-02 20:25

    PHP.net http://php.net/manual/en/function.array-unique.php

    array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

    Takes an input array and returns a new array without duplicate values.


    New solution:

    
    function remove_dupes(array $array){
        $ret_array = array();
        foreach($array as $key => $val){
            if(count(array_keys($val) > 1){
                continue;
            } else { 
                $ret_array[$key] = $val; 
            }
    }
    
    0 讨论(0)
提交回复
热议问题