php 将数组限制为 5 个项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15265723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Limit array to 5 items
提问by Jon87
I have a code that will add a number to an array each time a page is visited. the numbers are stored in a cookie and are retrieved later.
我有一个代码,每次访问页面时都会向数组添加一个数字。这些数字存储在 cookie 中,稍后可以检索。
I would like to keep only the 5 most recent numbers in the array.
我只想保留数组中最近的 5 个数字。
if the array is full (5 items) and a new number must be added, then the oldest number must be removed and the most recent items must be kept
如果数组已满(5 个项目)并且必须添加一个新数字,则必须删除最旧的数字并保留最新的项目
here's what i have:
这是我所拥有的:
$lastviewedarticles = array();
if (isset($_COOKIE["viewed_articles"]) ) {
$lastviewedarticles = unserialize($_COOKIE["viewed_articles"]);
}
if (!in_array($articleid, $lastviewedarticles)){
$lastviewedarticles[] = $articleid;
}
setcookie("viewed_articles", serialize($lastviewedarticles));
采纳答案by Alex Zheka
First of all i think, you need to obtain array length , then if length > or equal to 5, remove first element , and add element to the end of array.
首先,我认为,您需要获取数组长度,然后如果长度 > 或等于 5,则删除第一个元素,并将元素添加到数组的末尾。
if (!in_array($articleid, $lastviewedarticles)){
$count = count($lastviewedarticles);
if($count>=5)
array_shift($lastviewedarticles);
$lastviewedarticles[] = $articleid;
}
回答by Nirav Ranpara
array_slicereturns a slice of an array
array_slice返回数组的切片
array_slice($array, 0, 5) // return the first five elements
回答by silly
use array_splice and array_unique to get the 5 unique array values
使用 array_splice 和 array_unique 获得 5 个唯一的数组值
array_splice(array_unique($lastviewedarticles), 0, 5);
回答by Christoph Grimmer-Dietrich
Use a counter to access the array, increment it in every call and use the modulus operation to write into the array. If your counter has to persist over several calls you have to store it in a session variable or a cookie.
使用计数器访问数组,在每次调用中递增它并使用模数运算写入数组。如果您的计数器必须持续多次调用,您必须将其存储在会话变量或 cookie 中。
Assuming that $i holds your counter variable this would look like
假设 $i 持有您的计数器变量,这看起来像
if (!in_array($articleid, $lastviewedarticles)){
$lastviewedarticles[$i%5] = $articleid;
$i++;
}
The result is a primitive ring buffer that will always contain the last 5 values.
结果是一个原始的环形缓冲区,它总是包含最后 5 个值。

