【问题标题】:Sorting RecursiveArrayIterator对 RecursiveArrayIterator 进行排序
【发布时间】:2015-04-11 13:34:00
【问题描述】:

我有以下代码:

$itemA = array(
        'token' => "SOME_TOKEN",
        'default' => "DEFAULT A",
        'order' => 5
);
$itemB = array(
        'token' => "SOME__OTHER_TOKEN",
        'default' => "DEFAULT B",
        'order' => 2
);
$collection = new \RecursiveArrayIterator(array($itemA, $itemB));
$collection->uasort(function( $a, $b ) {
        if ($a['order'] === $b['order']) {
                return 0;
        }
        return ($a['order'] < $b['order']) ? -1 : 1;
});

应该对$collection 内部数组进行排序。事实上,确实如此,因为当我 var_dump($collection) - 我可以看到 $itemB 是第一个(因为它的顺序较低)。

但是 - 当我开始从 $collection 迭代项目时,我仍然将 $itemA 作为第一个元素。

很遗憾,documentation 没有提及该问题,这就是为什么我想知道这是一个错误还是我遗漏了什么?

更新

迭代代码:

while ($collection->valid())
{
    $current = $collection->current(); // current is already wrong :(
    ... do stuff ...
    $collection->next();
}

我的 php 版本是 5.3.10,以防万一。 要点failing unit test

【问题讨论】:

  • 在这里工作。请展示您如何迭代集合。 (顺便说一句,您的比较函数可以简单地为return $a['order'] - $b['order'];
  • @georg,感谢您的提示。
  • @georg,添加了迭代代码。但实际上,简单地调用 current 就足够了。我为更多细节创建了一个要点:gist.github.com/t1gor/3674e78251790362af00

标签: php iterator spl


【解决方案1】:

看起来uasort 影响了迭代器的内部current 指针,所以在循环之前需要$collection-&gt;rewind()。更好的是,不要使用while(valid),而是使用foreach,它会自动为您倒带:

$collection = new \RecursiveArrayIterator(...);
$collection->uasort(function( $a, $b ) {
    return $a['order'] - $b['order'];
});

foreach($collection as $item)
    print_r($item); // all fine

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-05
    • 2018-08-02
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多