Php 重新组织SplObjectStorage实例的子级
我有一个SplObjectStorage实例,它存储要在容器中呈现的元素对象。我希望能够有效地添加和删除对象从任何随机位置在商店 例如:Php 重新组织SplObjectStorage实例的子级,php,spl,Php,Spl,我有一个SplObjectStorage实例,它存储要在容器中呈现的元素对象。我希望能够有效地添加和删除对象从任何随机位置在商店 例如: <?php $store = new SplObjectStorageWrapper; $obj1 = new Obj; $obj2 = new Obj; $obj3 = new Obj; $store->attach($obj1); $store->attach($obj2); $store->insertAtIndex($obj3
<?php
$store = new SplObjectStorageWrapper;
$obj1 = new Obj;
$obj2 = new Obj;
$obj3 = new Obj;
$store->attach($obj1);
$store->attach($obj2);
$store->insertAtIndex($obj3, 1);
//Storage should now be organized as $obj1, $obj3, $obj2
事实证明,最简单(显然也是最有效)的方法是扩展SplObjectStorage
并使用LimitIterator
。代码示例如下:
<?php
/**
* Extends the SplObjectStorage class to provide index functions
*/
class ObjectStorage extends SplObjectStorage {
/**
* Returns the index of a given object, or false if not found
* @param object $object
*/
function indexOf($object){
if(!$this->contains($object)) return false;
foreach($this as $index => $obj) if($obj === $object) return $index;
}
/**
* Returns the object at the given index
*/
function itemAtIndex($index){
$it = new LimitIterator($this, $index, 1);
foreach($it as $obj) return $obj;
}
/**
* Returns the sequence of objects as specified by the offset and length
* @param int $offset
* @param int $length
*/
function slice($offset, $length){
$out = array();
$it = new LimitIterator($this, $offset, $length);
foreach($it as $obj) $out[] = $obj;
return $out;
}
/**
* Inserts an object (or an array of objects) at a certain point
* @param mixed $object A single object or an array of objects
* @param integer $index
*/
function insertAt($object, $index){
if(!is_array($object)) $object = array($object);
//Check to ensure that objects don't already exist in the collection
foreach($object as $k => $obj):
if($this->contains($obj)) unset($object[$k]);
endforeach;
//Do we have any objects left?
if(!$object) return;
//Detach any objects at or past this index
$remaining = array();
if($index < $this->count()):
$remaining = $this->slice($index, $this->count() - $index);
foreach($remaining as $obj) $this->detach($obj);
endif;
//Add the new objects we're splicing in
foreach($object as $obj) $this->attach($obj);
//Attach the objects we previously detached
foreach($remaining as $obj) $this->attach($obj);
}
/**
* Removes the object at the given index
* @param integer $index
*/
function removeAt($index){
$this->detach($this->itemAtIndex($index));
}
}
您是否需要SplObjectStorage的设置部分,例如无重复项?如果不是,请尝试使用SplPriorityQueue类。它的工作原理与insertAt不完全相同,但是对于您的用例来说,它可能已经足够好了。但由于性能上的巨大差异,我/确实/需要使用SplObjectStorage而不是基于阵列的解决方案。