Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/253.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
php数组删除重复/双重对象_Php_Arrays - Fatal编程技术网

php数组删除重复/双重对象

php数组删除重复/双重对象,php,arrays,Php,Arrays,在你走之前,所有的“问题”都在我身上。请读出情况 在我的应用程序中,我基于数据库中的数据构建对象。但是,有时由于sql查询中的LIKE语句(对当前用户组中的每个用户运行一次),同一数据库条目会被读取两次。因此,可能会创建多个相等的对象,根据array\u unique,这些对象不会被视为重复对象 //These objects are equal but are not duplicates. //And these cases need to be removed from the array

在你走之前,所有的“问题”都在我身上。请读出情况

在我的应用程序中,我基于数据库中的数据构建对象。但是,有时由于sql查询中的
LIKE
语句(对当前用户组中的每个用户运行一次),同一数据库条目会被读取两次。因此,可能会创建多个相等的对象,根据
array\u 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)

因此,问题是:有没有一种简单或更快的方法来从该阵列中删除任何重复项,而不是使用双循环?

可能是这样的:

$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);
    }
}

从t中选择不同的var1、var2、var3
查看@CrazySabpath,它确实非常出色。只需将我的所有变量添加到
\uuuu tostring()
@kpp,好吧,您没有确切指定对象的外观,一些var\u转储会有帮助,如果您的对象只有3个成员,那么为什么不呢?不过,如果可能的话,我建议Alma这样做,这应该在数据库级别(Sql)上解决。[P.s.那是讽刺吗?;d]我希望我能像Alma那样解决它,但就像我说的,查询会运行多次,但针对每个不同的用户,在某个点上,它有一个
like
语句,可能会导致重复,因为结果可能属于多个用户。但这是一个罕见的场合。(基本上,所有结果都属于一个组中的所有用户,但此表中未定义groupID,我不允许更改此表。因此,我被迫使用此海量查询筛选所有数据,这可能会导致某些重复。需要对这些数据进行筛选,以便向用户显示)。