How to remove all instances of duplicated values f

2020-02-28 15:50发布

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:

banna, banna, mango, mango, apple

Expected output:

apple

标签: php arrays
9条回答
走好不送
2楼-- · 2020-02-28 16:41

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; 
        }
}
查看更多
一纸荒年 Trace。
3楼-- · 2020-02-28 16:43

Only partially relevant to this specific question - but I created this function from Gumbo's answer for multi dimensional arrays:

function get_default($array)
{
    $default = array_column($array, 'default', 'id');
    $array = array_diff($default, array_diff_assoc($default, array_unique($default)));

    return key($array);
}

In this example, I had cached statuses and each one other than the default was 0 (the default was 1). I index the default array from the IDs, and then turn it into a string. So to be clear - the returned result of this is the ID of the default status providing it's in the same part of the multi dimensional array and not the key of it

查看更多
对你真心纯属浪费
4楼-- · 2020-02-28 16:44

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.

查看更多
登录 后发表回答