【问题标题】:PHP SplObjectStorage attach and push to top of the listPHP SplObjectStorage 附加并推送到列表顶部
【发布时间】:2012-09-19 12:31:35
【问题描述】:

我有一个小情况,我正在使用 SplObjectStorage 对象,在某些时候我需要附加一个项目,但还要将它推到列表的顶部,所以当我遍历这些项目时,我会将它作为第一个对象。

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

【问题讨论】:

  • 你有没有考虑过使用这种技术:当你需要添加这个元素的时候创建一个新的Storage,attach元素到它,然后addAll旧的storage到新的storage?

标签: php splobjectstorage


【解决方案1】:

我不确定iterators 是否存在这种情况,但这是iterator_to_arrayarray_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);
}

输出

object(stdClass)[2]
  public 'element' => string 'Last Element' (length=12)
object(stdClass)[4]
object(stdClass)[3]

【讨论】:

    猜你喜欢
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-31
    • 2013-09-19
    • 2021-08-07
    • 2020-05-24
    • 1970-01-01
    相关资源
    最近更新 更多