私は複数の要素を持つ配列を持っています。私は最近の10の値だけを残したいと思う。したがって、ループ内で配列を逆にして、要素が最初の10の範囲内にあるかどうかを確認し、そうでない場合、配列から要素の設定を解除します。最近の値が10個しかない配列
アンセットが機能しないという問題のみです。私は、要素を解除するために、キーを使用していますが、何とかこれは動作しません。アレイは成長を続けます。何か案は?
$currentitem = rand(0,100);
$lastproducts = unserialize($_COOKIE['lastproducts']);
$count = 0;
foreach(array_reverse($lastproducts) as $key => $lastproduct) {
if ($count <= 10) {
echo "item[$key]: $lastproduct <BR>";
}
else {
echo "Too many elements. Unsetting item[$key] with value $lastproduct <BR>";
unset($lastproducts[$key]);
}
$count = $count + 1;
}
array_push($lastproducts, $currentitem);
setcookie('lastproducts', serialize($lastproducts), time()+3600);
sidenote:解決策としてあなたの他のすべての問題をマーキングしてください、あなたに解決策を与えたものは?さもなければ、人々は彼らが解決されていないと思うし、より多くの回答を投稿するかもしれません。 –
チェックhttp://stackoverflow.com/questions/5468912/php-get-the-last-3-elements-of-an-arrayまたはhttp://stackoverflow.com/questions/3591867/how-to-get-最後の-n-items-in-a-ph-array-as-another-array –
@Sougata私はまったく同じことを提案しようとしていました。 ['array_slice()'](http://php.net/manual/en/function.array-slice.php)や['array_splice()'](http://php.net/manual/ ja/function.array-splice.php)?そのようにすれば、反転アレイをループする必要がなくなり、プロセスがより便利で効率的になります。 – px06