php Array删除重复/双重对象

时间:2014-06-05 10:57:17

标签: php arrays

在你对我提出“问题”的全部重复之前。请读出情况。

在我的应用程序中,我根据数据库中的数据构建对象。但是,有时我会发现由于我的sql查询中的LIKE语句(对于当前用户组中的每个用户运行一次),同一数据库条目被读取两次。因此,根据array_unique,可能会创建多个相等的对象,这些对象不会被视为重复对象。

//These objects are equal but are not duplicates.
//And these cases need to be removed from the array.
$z = new Obj(1,2,3);
$y = new Obj(1,2,3);

//code example
$e = array();

while($row = mysqli_fetch_array($result)){ //result is result from query.
    $a = $row['var1'];        //obtains data from result
    $b = $row['var2'];
    $c = $row['var3'];
    $d = new Obj($a, $b, $c); //Creates new object
    array_push($e, $d);       //Holds all objects
}

class Obj{

    public $a;
    public $b;
    public $c;

    public function __construct($a, $b, $c){
        $this->a = $a;
        $this->b = $b;
        $this->c = $c;
    }
}

//This could work but it is a slow(forbidden) algorithm.
foreach($e as $f){
    foreach($e as $g){
        //REMOVE DUPLICATES
    }
}

//This wont work because technically the 2 duplicates are 2 different objects.
//And not duplicates right?
$e = array_unique($e)

所以问题是:是否有一种简单或更快的方法从这个数组中删除任何重复项而不是使用双循环?

1 个答案:

答案 0 :(得分:0)

也许是这样的:

$e = array();
$ids = array();

while($row = mysqli_fetch_array($result)){ //result is result from query.
    $a = $row['var1'];        //obtains data from result
    $b = $row['var2'];
    $c = $row['var3'];
    $d = new Obj($a, $b, $c); //Creates new object
    $id = base64_encode(serialize($d));

    if (! in_array($id, $ids)) {
        array_push($e, $d);
        array_push($ids, $id);
    }
}