3

I have a little situation, I am using the SplObjectStorage object and at some point I need to attach an item but also push it to the top of the list so when I iterate through the items I will get it as first object.

i.e.

$splObj->attach($something)
$splOBj->attach($something2)
$splObj->attach($this_must_be_first);

// When I iterate
foreach($splOBj as $obj) {
    // I need the FIRST item to be the $this_must_be_first
}
ptheofan
  • 2,150
  • 3
  • 23
  • 36
  • Have you considered using this technique: creating a new Storage when you need to add this element, `attach` the element to it, then `addAll` old storage to the new storage? – raina77ow Sep 27 '12 at 16:50

1 Answers1

0

Am not sure if this exist for iterators but this is a simple work around with iterator_to_array and array_reverse

$splObj = new SplObjectStorage();

$last = new stdClass();
$last->element = "Last Element";


$splObj->attach(new stdClass());
$splObj->attach(new stdClass());
$splObj->attach($last);

$splArray = iterator_to_array($splObj);
$splArray = array_reverse($splArray);

foreach ($splArray as $obj)
{
    var_dump($obj);
}

Output

object(stdClass)[2]
  public 'element' => string 'Last Element' (length=12)
object(stdClass)[4]
object(stdClass)[3]
Baba
  • 94,024
  • 28
  • 166
  • 217