Possible Duplicate:
Getting last 5 elements of a php array
您好,我在一个数组中有 大约 11000 个项目,我只想显示 最后 5 或 10 项目
$i = 0;
foreach ($collection as $product_all) {
if($i==2) break;
echo $product_all->getId();
$neew = Mage::getModel('catalog/product')->load($product_all->getId());
echo'<pre>';
print_r($neew);
$i++;
}
有了这个我得到了前 2 项,我怎样才能只得到最后一项
这是 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();
这可以更改为(反向 ORDER,添加 LIMIT):
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->setOrder('id', 'desc')->setPageSize(5)->load();
瞧,只有最后 5 个项目被加载。
更好的是,您的代码看起来只需要 id,而不需要实际模型,因此可以将整个代码优化为:
$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
}