带有对象的数组,检查唯一成员

时间:2014-03-04 09:59:39

标签: php arrays

假设我有一个对象数组都有一个名为id的公共成员,我想删除所有“重复”:

这是我的尝试:

<?php


$a = new stdClass;
$a->id = 1;

$b = new stdClass;
$b->id = 2;

$c = new stdClass;
$c->id = 3;

$d = new stdClass;
$d->id = 1;

$objects = array($a, $b, $c, $d);

var_dump( (array) $objects);

echo '<hr>';

$temp = $objects;

foreach ($objects as &$object) {

    foreach ($temp as $object2) {
        if ($object2->id === $object->id) {
            unset($object);
            continue;
        }
    }

}

echo '<hr>';

var_dump($objects);

?>

Notice: Undefined variable: object in C:\Apache24\htdocs\objects.php on line 25

Notice: Trying to get property of non-object in C:\Apache24\htdocs\objects.php on line 25

我在这里缺少什么?是否有任何内置功能来实现这一目标呢?

2 个答案:

答案 0 :(得分:0)

我尝试了一种不同的方法,只有一个循环和一个将保留ids的临时数组

<?php

$a = new stdClass;
$a->id = 1;

$b = new stdClass;
$b->id = 2;

$c = new stdClass;
$c->id = 3;

$d = new stdClass;
$d->id = 1;

$objects = array($a, $b, $c, $d);

var_dump( (array) $objects);

echo '<hr>';

$temp = $array;
$ids = array();

foreach ($objects as  $object) {
    if (!in_array($object->id, $ids)) {
        $temp[] = $object;
        $ids[] = $object->id;
    }
}


echo '<hr>';

var_dump($objects);
var_dump($temp);

?>

答案 1 :(得分:0)

documentation comments中可以找到一个解决方案。 一旦适应了您的需要,就会像:

$a = new stdClass;
$a->id = 1;

$b = new stdClass;
$b->id = 2;

$c = new stdClass;
$c->id = 3;

$d = new stdClass;
$d->id = 1;

$objects = array($a, $b, $c, $d);
$idlist= array();
$callback = function($col)use(&$idlist){
    if(!isset($col->id)){
       $idlist[$col->id] = true;
       return true;
    }
    return false;
 }
$unique = array_filter( $array, $callback );
var_dump( $array );
var_dump( $unique );

就您当前的代码而言,您的错误来自“unset”指令。 你有两个循环,在最深的循环中你会破坏第一个循环创建的变量。如果这种破坏发生在迭代1,当你想在迭代2进行测试时,php说变量不存在,因为它实际上不再存在。