remove duplicates from array (array unic by key)

前端 未结 7 2234
一生所求
一生所求 2021-02-19 14:33
Array
(
    [0] => Array
        (
            [file] => /var/websites/example.com/assets/images/200px/1419050406e6648e1c766551a0ffc91380fd6ff3406002011-10-233750.         


        
7条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-19 14:37

    PHP does already have a function to remove duplicate elements from an array. But unfortunately, array_unique does only support string based comparisons:

    Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. The first element will be used.

    The problem is that any array turned into a string is equal to any other array:

    Arrays are always converted to the string "Array"; […]

    But you can use the uniqueness of array keys to solve this:

    $index = array();
    foreach ($arr as $key => $item) {
        if (isset($index[$item['md5']])) {
            unset($item[$key]);
        }
        $index[$item['md5']] = TRUE;
    }
    

提交回复
热议问题