如何使多维数组变得唯一?
我有一个如下所示的多维数组设置:
array(
[0]=>
array(
["name"]=> "Foo"
["slug"]=> "Bar"
)
[1]=>
array(
["name"]=> "Foo"
["slug"]=> "Bar"
)
[2]=>
array(
["name"]=> "Test 1"
["slug"]=> "test-1"
)
[3]=>
array(
["name"]=> "Test 2"
["slug"]=> "test-2"
)
[4]=>
array(
["name"]=> "Test 3"
["slug"]=> "test-3"
)
)
在该区域中搜索“名称”中的重复值并删除它们,以便多维数组中的每个值都是唯一的最佳方法是什么?
提前致谢!
I've got a multidimensional array setup like the following:
array(
[0]=>
array(
["name"]=> "Foo"
["slug"]=> "Bar"
)
[1]=>
array(
["name"]=> "Foo"
["slug"]=> "Bar"
)
[2]=>
array(
["name"]=> "Test 1"
["slug"]=> "test-1"
)
[3]=>
array(
["name"]=> "Test 2"
["slug"]=> "test-2"
)
[4]=>
array(
["name"]=> "Test 3"
["slug"]=> "test-3"
)
)
What would be the best way to search through the area for duplicates values in "name" and remove them, so that each value in the multidimensional array is unique?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用关联数组。
这将创建一个临时数组,使用
$v['name']
作为键。如果已经存在具有相同键的元素,则不会将其添加到临时数组中。您可以使用示例代码和输出将关联数组转换回顺序数组
: http://codepad.org/zHfbtUrl
You can use an associative array.
This creates a temporary array, using
$v['name']
as the key. If there is already an element with the same key, it is not added to the temporary array.You can convert the associative array back to a sequential array, using
Example code and output: http://codepad.org/zHfbtUrl
由于每个人都给出了替代方案,因此这里有一个解决当前问题的方案。有时我们必须处理我们拥有的数据,而不是按照我们喜欢的方式重新排列它。话虽这么说,这将从数组中删除所有重复的后续条目。
看起来像这样:
Since everyone given alternatives, here's a solution to the problem at-hand. Sometimes we have to work with the data we have, not re-arrange it the way we like it. That being said, this will remove all sub-sequent entries from the array that are duplicates.
Which will look like this:
只是看看你的具体情况,我建议使用哈希表而不是二维数组。如果您使用您的“姓名”作为哈希中的键,则每个条目都是唯一的。
对多维数组有特殊需求吗?
Just looking at your particular case, I would recommend using a hash table instead of a 2-dimensional array. If you use your "name" as the key in the hash, each entry would be unique.
Is there a specific need for the multidimensional array?
您可以在此处给出您的数组并给出一个冒号名称以使其唯一。
在此代码中,您有多维数组,我们 foreach 该数组,我们的列索引,我们推送该列值。当值相同时,它不添加返回数组。
所以这个解决方案适用于 1 列的 array_unique 。
You can give your array here and give a colon name for making unique.
On this code, you have multidimensonal array, we foreach that array, which column index for us, we pushing that column values. And when same value, its not adding return array.
So this solution for array_unique for 1 coloumn.
对于多维数组来说,解决方案要简单得多。
Much simpler solution for your multidimensional array.