获取每个 php 中的最后一项


Get last items in foreach php

可能的重复项:
获取 php 数组的最后 5 个元素

嗨,我

在一个数组中有大约 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();

这可以更改为(反向顺序,添加限制):

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

http://php.net/manual/en/function.array-slice.php

$items = array_slice($items, -5);

尝试array_slice php 函数。

如果要保留键,可以将 true 作为第四个参数传入:

array_slice($a, -5, 5, true);

您可以使用array_slice

$last = array_slice($collection, -5);

使用您的代码示例...

$i = 0;
$no = count($collection);
foreach ($collection as $product_all) { 
 if($i >= ($no-10)) {
     echo $product_all->getId();        
     $neew = Mage::getModel('catalog/product')->load($product_all->getId());         
     echo'<pre>';
     print_r($neew); 
  }
  $i++; 
}

试试这个

<?php
$array  = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
function foreach_last($array, $n, $func) {
    reset($array);
    end($array);
    $i  = 0;
    $n  = min($n, count($array)) - 1;
    while ( $i ++ < $n ) 
        prev($array);
    $func(current($array), key($array));
    while ( $v = next($array) ) {
        $func($v, key($array));
    }
}
function print_e($v, $k) {
    printf("k: %s, v: %s'n", $k, $v);
}
foreach_last($array, 5, 'print_e');

如果你想要最后X项:

$i = 0;
$totalCount = count($collection);
$itemsCount = 5; 
$x = $totalCount - $itemsCount;
foreach ($collection as $product_all) {
    if ($i < $x) {
        $i++;
        continue;
    }
    echo $product_all->getId();
    $neew = Mage::getModel('catalog/product')->load($product_all->getId());
    echo'<pre>';
    print_r($neew);
    $i++;
}

如果您只想要最后一个,您可以使用:

$lastItem = $collection->getLastItem();

但最好的解决方案是根据我的说法对你的收藏进行分类和限制。如果您只想使用其中 5 或 10 个,为什么要获取 11000+ 个产品 (!)?如果您获得的产品没有任何排序,那么我记得它们按created_at属性排序。您可以简单地按降序排序并限制为 X .