这是Magento,$collection
不是一个数组,而是一个迭代器。这意味着像array_slice
阵列功能不工作,但你可以模拟像,在相反的顺序一个foreach:
end($collection);
while($current = current($collection)) {
// ... (see below)
prev($collection);
}
在循环中,你会建造你的最后5个项目阵列,打破你必须照顾他们:
$lastFive[] = $current;
if (count($lastFive) == 5) break;
编辑:现在我们已经解决了您的直接问题,让我们来谈谈性能。从数据库中获取11000个项目到内存中是一个非常糟糕的主意,只能使用5个或10个项目。您应该找到$collection
加载并从那里开始的代码。这是最有可能是这样的:
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->setOrder('id', 'asc')->load();
这可能被更改为(相反的顺序,添加LIMIT):
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->setOrder('id', 'desc')->setPageSize(5)->load();
瞧,只有最后5个项目得到加载。
更棒的是,你的代码看起来像你只需要身份证,而不是实际的车型,所以整个事情可以优化到:
$collection = Mage::getModel('catalog/product')->getCollection();
$ids = $collection->setOrder('id', 'desc')->setPageSize(5)->getAllIds();
foreach ($ids as $id) {
$product = Mage::getModel('catalog/product')->load($id);
// do what you want
}
看到这个答案 http://stackoverflow.com/questions/9704983/getting-last-5-elements-of-a-php-array – philipbrown
philipbrown,如果它是一个数组,不是迭代器 - 仍然是一个可能的假设;-) – VolkerK