PHP:按值对对象数组进行分组的函数 [英] PHP: Function to group array of objects by value

查看:35
本文介绍了PHP:按值对对象数组进行分组的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个多维数组.如何按值删除重复项?在以下数组中,[0]、[2] 和 [5] 具有相同的 [ID].是否有一个函数可以根据特定值删除任何重复的数组?在这种情况下,我想删除数组 [2] 和数组 [5],因为它们具有与数组 [0] 相同的 [ID].

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
        )

)

推荐答案

一种方法:($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)

$new_array = array();
foreach ($old_array as $item)
  if (!array_key_exists($item->ID, $new_array))
    $new_array[$item->ID] = $item;

(我还没有测试过,但应该可以)

(I haven't tested this, but it should work)

这篇关于PHP:按值对对象数组进行分组的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆