php PHP按值唯一数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6422562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:20:56  来源:igfitidea点击:

PHP unique array by value?

phparraysunique

提问by Jens T?rnell

I have an array in PHP that looks like this:

我在 PHP 中有一个数组,如下所示:

  [0]=>
       array(2) {
           ["name"]=>
              string(9) "My_item"
           ["url"]=>
              string(24) "http://www.my-url.com/"
       }
  [1]=>
     array(2) {
         ["name"]=>
             string(9) "My_item"
         ["url"]=>
            string(24) "http://www.my-url2.com/"
     }

The two values in "name" are the same in this two items. I want to sort out duplicates like this.

“name”中的两个值在这两项中是相同的。我想整理出这样的重复项。

How do I create an unique array by checking the "name" value?

如何通过检查“名称”值来创建唯一数组?

回答by user187291

basically

基本上

foreach($your_array as $element) {
    $hash = $element[field-that-should-be-unique];
    $unique_array[$hash] = $element;
}

回答by GordyD

Serialisationis very useful for simplifying the process of establishing the uniqueness of a hierarchical array. Use this one liner to retrieve an array containing only unique elements.

序列化对于简化建立分层数组唯一性的过程非常有用。使用这个一个 liner 来检索一个只包含唯一元素的数组。

$unique = array_map("unserialize", array_unique(array_map("serialize", $input)));

回答by Rakesh Sankar

Please find this link useful, uses md5 hash to examine the duplicates:

请发现此链接有用,使用 md5 哈希检查重复项:

http://www.phpdevblog.net/2009/01/using-array-unique-with-multidimensional-arrays.html

http://www.phpdevblog.net/2009/01/using-array-unique-with-multidimensional-arrays.html

Quick Glimpse:

快速一瞥:

/**
 * Create Unique Arrays using an md5 hash
 *
 * @param array $array
 * @return array
 */
function arrayUnique($array, $preserveKeys = false)
{
    // Unique Array for return
    $arrayRewrite = array();
    // Array with the md5 hashes
    $arrayHashes = array();
    foreach($array as $key => $item) {
        // Serialize the current element and create a md5 hash
        $hash = md5(serialize($item));
        // If the md5 didn't come up yet, add the element to
        // to arrayRewrite, otherwise drop it
        if (!isset($arrayHashes[$hash])) {
            // Save the current element hash
            $arrayHashes[$hash] = $hash;
            // Add element to the unique Array
            if ($preserveKeys) {
                $arrayRewrite[$key] = $item;
            } else {
                $arrayRewrite[] = $item;
            }
        }
    }
    return $arrayRewrite;
}

$uniqueArray = arrayUnique($array);
var_dump($uniqueArray);

See the working example here: http://codepad.org/9nCJwsvg

请参阅此处的工作示例:http: //codepad.org/9nCJwsvg

回答by Kai-Tobias Bartholome

Simple Solution:

简单的解决方案:

/**
 * @param $array
 * @param null $key
 * @return array
 */
public static function unique($array,$key = null){
    if(null === $key){
        return array_unique($array);
    }
    $keys=[];
    $ret = [];
    foreach($array as $elem){
        $arrayKey = (is_array($elem))?$elem[$key]:$elem->$key;
        if(in_array($arrayKey,$keys)){
            continue;
        }
        $ret[] = $elem;
        array_push($keys,$arrayKey);
    }
    return $ret;
}

回答by Медведев Александр

function unique_multidim_array($array, $key) { 
            $temp_array = array(); 
            $i = 0; 
            $key_array = array(); 

            foreach($array as $val) { 
                if (!in_array($val[$key], $key_array)) { 
                    $key_array[$i] = $val[$key]; 
                    $temp_array[$i] = $val; 
                } 
                $i++; 
            } 
            return $temp_array; 
        } 
$result = unique_multidim_array($visitors,'ip');

回答by symcbean

Given that the keys on the array (0,1) do not seem to be significant a simple solution would be to use the value of the element referenced by 'name' as the key for the outer array:

鉴于数组 (0,1) 上的键似乎并不重要,一个简单的解决方案是使用“name”引用的元素的值作为外部数组的键:

["My_item"]=>
   array(2) {
       ["name"]=>
          string(9) "My_item"
       ["url"]=>
          string(24) "http://www.my-url.com/"
   }

...and if there is only one value other than the 'name' why bother with a nested array at all?

...如果除了“名称”之外只有一个值,为什么还要麻烦嵌套数组呢?

["My_item"]=>"http://www.my-url.com/"