PHP:从数组中删除对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3573313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:16:22  来源:igfitidea点击:

PHP : Remove object from array

phparraysobject

提问by danidacar

What is an elegant way to remove an object from an array of objects in PHP ?

从 PHP 中的对象数组中删除对象的优雅方法是什么?

Just to be clear ..

只是要清楚..

class Data{

  private $arrObservers;

  public add(Observer $o) {  
    array_push($this->arrObservers, $o);  
  }    
  public remove(Observer $o) {  
    // I NEED THIS CODE to remove $o from $this->arrObservers
  }  

}

回答by Gordon

You can do

你可以做

function unsetValue(array $array, $value, $strict = TRUE)
{
    if(($key = array_search($value, $array, $strict)) !== FALSE) {
        unset($array[$key]);
    }
    return $array;
}

You can also use spl_object_hashto create a hash for the objects and use that as array key.

您还可以使用spl_object_hash为对象创建哈希并将其用作数组键。

However, PHP also has a native Data Structure for Object collections with SplObjectStorage:

但是,PHP 还具有用于对象集合的本机数据结构SplObjectStorage

$a = new StdClass; $a->id = 1;
$b = new StdClass; $b->id = 2;
$c = new StdClass; $c->id = 3;

$storage = new SplObjectStorage;
$storage->attach($a);
$storage->attach($b);
$storage->attach($c);
echo $storage->count(); // 3

// trying to attach same object again
$storage->attach($c);
echo $storage->count(); // still 3

var_dump( $storage->contains($b) ); // TRUE
$storage->detach($b);
var_dump( $storage->contains($b) ); // FALSE

SplObjectStorageis Traversable, so you can foreachover it as well.

SplObjectStorageis Traversable,所以你也可以foreach超越它。

On a sidenote, PHP also has native interfaces for Subjectand Observer.

附带说明一下,PHP 还具有用于SubjectObserver 的本机接口。

回答by icio

I agree with the answers above, but for the sake of completeness (where you may not have unique IDs to use as a key) my preferred methods of removing values from an array are as follows:

我同意上面的答案,但为了完整起见(您可能没有唯一的 ID 用作键),我从数组中删除值的首选方法如下:

/**
 * Remove each instance of a value within an array
 * @param array $array
 * @param mixed $value
 * @return array
 */
function array_remove(&$array, $value)
{
    return array_filter($array, function($a) use($value) {
        return $a !== $value;
    });
}

/**
 * Remove each instance of an object within an array (matched on a given property, $prop)
 * @param array $array
 * @param mixed $value
 * @param string $prop
 * @return array
 */
function array_remove_object(&$array, $value, $prop)
{
    return array_filter($array, function($a) use($value, $prop) {
        return $a->$prop !== $value;
    });
}

Which are used in the following way:

它们以下列方式使用:

$values = array(
    1, 2, 5, 3, 5, 6, 7, 1, 2, 4, 5, 6, 6, 8, 8,
);
print_r(array_remove($values, 6));

class Obj {
    public $id;
    public function __construct($id) {
        $this->id = $id;
    }
}
$objects = array(
    new Obj(1), new Obj(2), new Obj(4), new Obj(3), new Obj(6), new Obj(4), new Obj(3), new Obj(1), new Obj(5),
);
print_r(array_remove_object($objects, 1, 'id'));

Hope that helps.

希望有帮助。

回答by Cody Snider

I recommend using the ID (if you have one, anything that will be unique to that object should work within reason) of the object as the array key. This way you can address the object within the array without having to run through a loop or store the ID in another location. The code would look something like this:

我建议使用对象的 ID(如果你有一个,任何对该对象唯一的东西都应该在合理范围内工作)作为数组键。通过这种方式,您可以在数组中寻址对象,而无需运行循环或将 ID 存储在另一个位置。代码看起来像这样:

$obj_array[$obj1->getId()] = $obj1;
$obj_array[$obj2->getId()] = $obj2;
$obj_array[$obj3->getId()] = $obj3;

unset($obj_array[$object_id]);

UPDATE:

更新:

class Data{

  private $arrObservers;

  public add(Observer $o) {  
    $this->arrObservers[$o->getId()] = $o;  
  }    
  public remove(Observer $o) {  
    unset($this->arrObservers[$o->getId()]);
  }  

}

回答by Tatu Ulmanen

unset($myArray[$index]);where $indexis the index of the element you want to remove. If you wan't a more specific answer, show some code or describe what you're trying to do.

unset($myArray[$index]);where$index是要删除的元素的索引。如果您不需要更具体的答案,请显示一些代码或描述您要执行的操作。

回答by Alex Pliutau

$obj_array['obj1'] = $obj1;
$obj_array['obj2'] = $obj2;
$obj_array['obj3'] = $obj3;
unset($obj_array['obj3']);

回答by thinice

Use this for your internal object storage instead: http://us2.php.net/manual/en/class.splobjectstorage.php

将此用于您的内部对象存储:http: //us2.php.net/manual/en/class.splobjectstorage.php

回答by Softmixt

 function obj_array_clean ($array, $objId)
 {
    $new = array() ;
    foreach($array as $value)
    {
        $new[$value->{$objId}] = $value;
    }
    $array = array_values($new);
    return $array;
 }

 $ext2 = obj_array_clean($ext, 'OnjId');
  • It will remove the duplicate object "OnjId" from array objects $array.
  • 它将从数组对象 $array 中删除重复的对象“OnjId”。

回答by tomloprod

For remove an object from a multi dimensional arrayyou can use this:

要从 a 中删除对象,multi dimensional array您可以使用:

$exampleArray= [
    [
      "myKey"=>"This is my key",
      "myValue"=>"10"
    ],
    [
      "myKey"=>"Oh!",
      "myValue"=>"11"
    ]
];

With array_columnyou can specify your key column name:

有了array_column你可以指定你的键列名:

if(($key = array_search("Oh!", array_column($exampleArray, 'myKey'))) !== false) {
    unset($exampleArray[$key]);
}

And this will remove the indicated object.

这将删除指示的对象。

回答by Minwork

If you want to remove one or more objects from array of objects (using spl_object_hash to determine if objects are the same) you can use this method:

如果要从对象数组中删除一个或多个对象(使用 spl_object_hash 确定对象是否相同),可以使用此方法:

$this->arrObservers = Arr::diffObjects($this->arrObservers, [$o]);

from this library.

这个图书馆

回答by Vaibhav Malushte

Try this, will solve your problem.

试试这个,会解决你的问题。

class Data{
  private $arrObservers;

  public add(Observer $o) {  
    array_push($this->arrObservers,$o);  
  }    

  public remove($Observer $o) {  
    unset($this->arrObservers[$o]);  
  }  
}