根据对象属性从数组中删除重复项?

时间:2012-05-08 20:10:02

标签: php object multidimensional-array duplicate-removal

我有一个对象数组。我想根据对象中的“name”值删除重复项。

  [0]=>
  object(stdClass)#337 (9) {
    ["term_id"]=>
    string(2) "23"
    ["name"]=>
    string(12) "Assasination"
    ["slug"]=>
    string(12) "assasination"
  }
  [1]=>
  object(stdClass)#44 (9) {
    ["term_id"]=>
    string(2) "14"
    ["name"]=>
    string(16) "Campaign Finance"
    ["slug"]=>
    string(16) "campaign-finance"
  }
  [2]=>
  object(stdClass)#298 (9) {
    ["term_id"]=>
    string(2) "15"
    ["name"]=>
    string(16) "Campaign Finance"
    ["slug"]=>
    string(49) "campaign-finance-good-government-political-reform"
  }

因此,在这种情况下,如何从阵列中删除重复的“Campaign Finance”对象。那么整个[2]对象呢?

我在这里经历了一堆PHP重复数组问题,但似乎没有人处理对象并只过滤一个参数。

5 个答案:

答案 0 :(得分:12)

使用现有密钥和名称作为值构建新数组,使用array_unique(请注意,它会保留密钥)。

然后从原始键中删除不在唯一“< ed”数组中的所有内容。

编辑:完整示例:

class my_obj
{
        public $term_id;
        public $name;
        public $slug;

        public function __construct($i, $n, $s)
        {
                $this->term_id = $i;
                $this->name = $n;
                $this->slug = $s;
        }
}

$objA = new my_obj(23, "Assasination", "assasination");
$objB = new my_obj(14, "Campaign Finance", "campaign-finance");
$objC = new my_obj(15, "Campaign Finance", "campaign-finance-good-government-political-reform");

$array = array($objA, $objB, $objC);

echo "Original array:\n";
print_r($array);

/** Answer Code begins here **/

// Build temporary array for array_unique
$tmp = array();
foreach($array as $k => $v)
    $tmp[$k] = $v->name;

// Find duplicates in temporary array
$tmp = array_unique($tmp);

// Remove the duplicates from original array
foreach($array as $k => $v)
{
    if (!array_key_exists($k, $tmp))
        unset($array[$k]);
}

/** Answer Code ends here **/

echo "After removing duplicates\n";
print_r($array);

输出:

Original array:
Array
(
    [0] => my_obj Object
        (
            [term_id] => 23
            [name] => Assasination
            [slug] => assasination
        )

    [1] => my_obj Object
        (
            [term_id] => 14
            [name] => Campaign Finance
            [slug] => campaign-finance
        )

    [2] => my_obj Object
        (
            [term_id] => 15
            [name] => Campaign Finance
            [slug] => campaign-finance-good-government-political-reform
        )

)
After removing duplicates
Array
(
    [0] => my_obj Object
        (
            [term_id] => 23
            [name] => Assasination
            [slug] => assasination
        )

    [1] => my_obj Object
        (
            [term_id] => 14
            [name] => Campaign Finance
            [slug] => campaign-finance
        )

)

删除了term_id 15的对象,因为它与term_id 14具有相同的名称。

答案 1 :(得分:1)

我正在寻找一个很好的答案而且找不到一个,所以我写了我自己的处理这个案例的情况,以及你希望根据多个属性去掉电子邮件的情况

$array = DeDupeArrayOfObjectsByProps($array, ['name']);

这是通用功能:

/**
 * Iterates over the array of objects and looks for matching property values.
 * If a match is found the later object is removed from the array, which is returned
 * @param array $objects    The objects to iterate over
 * @param array $props      Array of the properties to dedupe on.
 *   If more than one property is specified then all properties must match for it to be deduped.
 * @return array
 */
public function DeDupeArrayOfObjectsByProps($objects, $props) {
    if (empty($objects) || empty($props))
        return $objects;
    $results = array();
    foreach ($objects as $object) {
        $matched = false;
        foreach ($results as $result) {
            $matchs = 0;
            foreach ($props as $prop) {
                if ($object->$prop == $result->$prop)
                    $matchs++;
            }
            if ($matchs == count($props)) {
                $matched = true;
                break;
            }

        }
        if (!$matched)
            $results[] = $object;
    }
    return $results;
}

以下是您案件的完整用法:

class my_obj {
    public $term_id;
    public $name;
    public $slug;

    public function __construct($i, $n, $s) {
        $this->term_id = $i;
        $this->name = $n;
        $this->slug = $s;
    }
}

$objA = new my_obj(23, "Assasination", "assasination");
$objB = new my_obj(14, "Campaign Finance", "campaign-finance");
$objC = new my_obj(15, "Campaign Finance", "campaign-finance-good-government-political-reform");
$array = array($objA, $objB, $objC);

$array = DeDupeArrayOfObjectsByProps($array, ['name']);
var_dump($array);

答案 2 :(得分:1)

我需要同样的事情...... 这就是我所做的(基于this post

为数组和对象工作
function my_array_unique_by_subkey($array,$subkey){

    $temp = array();

    $unique = array_filter($array, function ($v) use (&$temp,$subkey) {

        if ( is_object($v) ) $v = (array)$v;

        if ( !array_key_exists($subkey,$v) ) return false;

        if ( in_array($v[$subkey], $temp) ) {
            return false;
        } else {
            array_push($temp, $v[$subkey]);
            return true;
        }
    });

    return $unique;
}

答案 3 :(得分:1)

单线:

$filtered = array_intersect_key($array, array_unique(array_column($array, 'someProperty')));

请注意,array_column()可用于PHP 7及更高版本的对象数组。

答案 4 :(得分:0)

稍微偏离主题,但密切相关:仅通过实例重复数据删除对象数组的最短路径:

/**
 * The array must NOT contain scalars.
 *
 * @param mixed[] $objects
 * @return mixed[]
 */
public static function arrayUniqueForObjects(array $objects): array
{
    $deDuplicatedArray = [];

    foreach ($objects as $object) {
        $deDuplicatedArray[spl_object_hash($object)] = $object;
    }

    return array_values($deDuplicatedArray);
}