基于键的PHP多维数组去除重复项

4

我有一个多维数组($array),其中的条目看起来像:

{ ["upload/example.gif"]=> array(5) { 
     ["title"]=> string(12) "This is me" 
     ["excerpt"]=> string(24) "This is a photo of a tree" 
     ["img"]=> string(42) "upload/example.gif"
     ["link"]=> string(23) "http://www.google.co.uk" 
     ["source"]=> string(6) "custom" 
   }
}

我需要能够根据键名从$array中删除任何重复的值。如果我的数组是:

$array = array( ["upload/example.gif"] => etc....
                ["upload/tree.gif"] => etc....
                ["upload/example.gif"] => etc....)

我可以删除其中一个["upload/example.gif"] => etc....数组。

我尝试过:

$array = array_map('unserialize', array_unique(array_map('serialize', $array)));

但是那并没有起作用。
提前感谢。

13
在数组中,不允许有重复的键名(索引),否则会被覆盖。因此所有的键名都是自动唯一的。 - netcoder
1
请参阅 http://php.net/manual/en/language.types.array.php。如果未为值指定键,则将使用整数索引的最大值作为新键,并且该值加1。如果指定了已经分配了值的键,则该值将被覆盖。 - Treffynnon
@netcoder - 我认为你的评论可以作为答案。 - Álvaro González
@netcoder - 谢谢,这帮助我解决了问题。 - BobFlemming
1个回答

0

netcoder 合理回答了问题,我只是希望它出现在答案框中(而不是评论中)。

在关联数组(或任何数组)中,您不能具有重复的键。由于它是一个数组,您可以保证拥有唯一的键。

顺便说一下,如果您发现不同的键中存在重复数据,则可以通过取消设置相应的键来删除冗余键。

unset($array['delete_me']);

http://php.net/manual/en/function.unset.php


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接