2016-12-02 6 views
0

私は複数の要素を持つ配列を持っています。私は最近の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); 
+2

sidenote:解決策としてあなたの他のすべての問題をマーキングしてください、あなたに解決策を与えたものは?さもなければ、人々は彼らが解決されていないと思うし、より多くの回答を投稿するかもしれません。 –

+1

チェック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 –

+0

@Sougata私はまったく同じことを提案しようとしていました。 ['array_slice()'](http://php.net/manual/en/function.array-slice.php)や['array_splice()'](http://php.net/manual/ ja/function.array-splice.php)?そのようにすれば、反転アレイをループする必要がなくなり、プロセスがより便利で効率的になります。 – px06

答えて

0

私は最後の10を選択するための良い方法だと思いますされています。最後に、$selectionは10、最後の(またはそれ以下)の製品を持っています

$selection = array(); 
foreach(array_reverse($lastproducts) as $key => $lastproduct) { 
    $selection[$key] = $lastproduct; 
    if (count($selection)>=10) break; 
} 

0

この目的でarray_splice($input, $offset)関数を使用できます。

$last_items_count = 10; 
if(count($lastproducts) >= $last_items_count) { 
    $lastproducts = array_splice($lastproducts, count($lastproducts) - $last_items_count); 
} 

var_dump($lastproducts); 

このコードが役立つことを望みます。詳細については

は、こちらのドキュメントです:

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

0

私はarray_slice(http://php.net/array_slice)おそらくのように使用したい:

$lastproducts = unserialize($_COOKIE['lastproducts']); 
// add on the end ... 
$lastproducts[] = $newproduct; 
// start at -10 from the end, give me 10 at most 
$lastproducts = array_slice($lastproducts, -10); 
// .... 
+1

'array_slice($ lastproducts、-10); 'だけで十分です。 'length'パラメータを指定する必要はありません。あなたの答えを編集してください。 – Perumal

0
array_spliceとarray_sliceを使用して素晴らしい作品

、感謝を! :)

$lastproducts = unserialize($_COOKIE['lastproducts']); 

// remove this product from array 
$lastproducts = array_diff($lastproducts, array($productid)); 

// insert product on first position in array 
array_splice($lastproducts, 0, 0, $productid); 

// keep only first 15 products of array 
$lastproducts = array_slice($lastproducts, 0, 15); 
関連する問題