PHP:按值对对象数组进行分组的函数
我正在使用多维数组。如何按值删除重复项?在以下数组中,[0]、[2] 和 [5] 具有相同的 [ID]。是否有一个函数可以根据特定值删除任何重复的数组?在这种情况下,我想删除数组 [2] 和数组 [5],因为它们具有与数组 [0] 相同的 [ID]。
感谢您提供的任何信息。
Array
(
[0] => stdClass Object
(
[d] => 2010-10-18 03:30:04
[ID] => 9
)
[1] => stdClass Object
(
[d] => 2010-10-18 03:30:20
[ID] => 4
)
[2] => stdClass Object
(
[d] => 2010-11-03 16:46:34
[ID] => 9
)
[3] => stdClass Object
(
[d] => 2010-11-02 03:19:14
[ID] => 1
)
[4] => stdClass Object
(
[d] => 2010-05-12 04:57:34
[ID] => 2
)
[5] => stdClass Object
(
[d] => 2010-05-10 05:24:15
[ID] => 9
)
)
I am working with a multi-dimensional array. How can I remove duplicates by value? In the following array, [0], [2] and [5] have the same [ID]. Is there a function that will remove any duplicate arrays based on a particular value? In this case, I would like to remove array [2] and array [5], as they have the same [ID] as array [0].
Thank you for any information you may have.
Array
(
[0] => stdClass Object
(
[d] => 2010-10-18 03:30:04
[ID] => 9
)
[1] => stdClass Object
(
[d] => 2010-10-18 03:30:20
[ID] => 4
)
[2] => stdClass Object
(
[d] => 2010-11-03 16:46:34
[ID] => 9
)
[3] => stdClass Object
(
[d] => 2010-11-02 03:19:14
[ID] => 1
)
[4] => stdClass Object
(
[d] => 2010-05-12 04:57:34
[ID] => 2
)
[5] => stdClass Object
(
[d] => 2010-05-10 05:24:15
[ID] => 9
)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
一种方法是:(
$old_array
是你的数组,$new_array
将包含新数组,删除重复项,由该 ID 键入)(我还没有测试过这个,但它应该有效)
One way to do it: (
$old_array
is your array, and$new_array
will contain the new one, dupes removed, keyed by that ID)(I haven't tested this, but it should work)
您可以使用茴香酒好东西来做到这一点:
请参阅http://ouzo.readthedocs.org/en/latest/utils/ Fluent_array.html#uniqueby
You can do it with ouzo goodies:
See http://ouzo.readthedocs.org/en/latest/utils/fluent_array.html#uniqueby
我认为循环并构造一个新数组是最简单的。在循环中,使用 array_key_exists() 判断新数组中是否已存在该 ID,如果不存在,则追加一个元素。
I think it would be easiest to loop through and construct a new array. In the loop, use array_key_exists() to determine if the ID already exists in the new array, and if not, append an element.
它不是一个多维数组,而是一个对象数组。您可以对其进行循环(此示例更改了数组):
您还可以创建一个新数组并将对象添加到新数组中。
It is not a multidimensional array, it is an array of objects. You can just loop over it (this example changes the array in place):
You can also create a new array and add the objects to the new array.
请注意第二个 foreach 中的循环引用。
Note the loop-by-reference in the second foreach.
从 索引 函数检查="https://github.com/ihor/Nspl" rel="nofollow">Nspl。
Check indexed function from Nspl.