【发布时间】:2012-03-31 02:10:21
【问题描述】:
如何获取 PHP 数组的最后 5 个元素?
我的数组是由 MySQL 查询结果动态生成的。长度不是固定的。如果长度小于或等于 5,则获取全部,否则获取最后的 5。
我尝试了 PHP 函数 last() 和 array_pop(),但它们只返回最后一个元素。
【问题讨论】:
-
请在代码中显示动态生成的无长度数组。
如何获取 PHP 数组的最后 5 个元素?
我的数组是由 MySQL 查询结果动态生成的。长度不是固定的。如果长度小于或等于 5,则获取全部,否则获取最后的 5。
我尝试了 PHP 函数 last() 和 array_pop(),但它们只返回最后一个元素。
【问题讨论】:
我只是想稍微扩展一下这个问题。如果您循环浏览一个大文件并希望保留当前位置的最后 5 行或 5 个元素怎么办。并且您不想在内存中保留庞大的数组并遇到 array_slice 的性能问题。
这是一个实现 ArrayAccess 接口的类。
它获取数组和所需的缓冲区限制。
您可以像使用数组一样使用类对象,但它会自动仅保留最后 5 个元素
<?php
class MyBuffer implements ArrayAccess {
private $container;
private $limit;
function __construct($myArray = array(), $limit = 5){
$this->container = $myArray;
$this->limit = $limit;
}
public function offsetSet($offset, $value) {
if (is_null($offset)) {
$this->container[] = $value;
} else {
$this->container[$offset] = $value;
}
$this->adjust();
}
public function offsetExists($offset) {
return isset($this->container[$offset]);
}
public function offsetUnset($offset) {
unset($this->container[$offset]);
}
public function offsetGet($offset) {
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
public function __get($offset){
return isset($this->container[$offset]) ? $this->container[$offset] : null;
}
private function adjust(){
if(count($this->container) == $this->limit+1){
$this->container = array_slice($this->container, 1,$this->limit);
}
}
}
$buf = new MyBuffer();
$buf[]=1;
$buf[]=2;
$buf[]=3;
$buf[]=4;
$buf[]=5;
$buf[]=6;
echo print_r($buf, true);
$buf[]=7;
echo print_r($buf, true);
echo "\n";
echo $buf[4];
【讨论】:
使用array_slice和count()很简单
$arraylength=count($array);
if($arraylength >5)
$output_array= array_slice($array,($arraylength-5),$arraylength);
else
$output_array=$array;
【讨论】:
array_slice($array, -5) 应该可以解决问题
【讨论】:
【讨论】:
$items 只有 3 个元素会怎样?
array_pop() 循环 5 次?如果返回值为null,则表示数组已用尽。
$lastFive = array();
for($i=0;$i < 5;$i++)
{
$obj = array_pop($yourArray);
if ($obj == null) break;
$lastFive[] = $obj;
}
看到其他答案后,我不得不承认array_slice() 看起来更短且更具可读性。
【讨论】: