PHP 按值唯一数组

发布于 2024-11-16 13:15:14 字数 454 浏览 7 评论 0原文

我在 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/"
     }

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

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

I have an array in PHP that looks like this:

  [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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

请爱~陌生人 2024-11-23 13:15:14

基本上

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

Basically

$unique_array = [];
foreach($your_array as $element) {
    $hash = $element[field-that-should-be-unique];
    $unique_array[$hash] = $element;
}
$result = array_values($unique_array);
滥情哥ㄟ 2024-11-23 13:15:14

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

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

Serialisation is 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.

$unique = array_map("unserialize", array_unique(array_map("serialize", $input)));
你在我安 2024-11-23 13:15:14

请发现此链接很有用。它使用 MD5 哈希来检查重复项:

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

快速浏览:

/**
 * 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);

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

Please find this link useful. It uses an MD5 hash to examine the duplicates:

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

笑,眼淚并存 2024-11-23 13:15:14

简单的解决方案:

/**
 * @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;
}

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;
}
め七分饶幸 2024-11-23 13:15:14
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');
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');
攒眉千度 2024-11-23 13:15:14

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

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

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

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

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:

["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/"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文