Tôi chỉ muốn kéo dài câu hỏi một chút. Điều gì sẽ xảy ra nếu bạn lặp lại mặc dù một tệp lớn và muốn giữ 5 dòng cuối cùng hoặc 5 phần tử từ một vị trí hiện tại. Và bạn không muốn giữ mảng lớn trong bộ nhớ và gặp vấn đề với hiệu suất của array_slice.
Đây là lớp triển khai giao diện ArrayAccess.
Nó nhận được giới hạn bộ đệm mong muốn.
Bạn có thể làm việc với các đối tượng lớp như nó là một mảng nhưng nó sẽ tự động giữ CHỈ cuối cùng 5 yếu tố
<?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];
Hãy thể hiện, trong mã, mảng tạo động mà không có chiều dài. –