2012-01-17 23 views
0

我正在使用PHP,我試圖通過$_SESSION數組保留最後10個帖子ID在WordPress中的數組。我知道我可以添加最新帖子ID如下:PHP - 如何保持數組中的最後十個東西?

$_SESSION['recently_viewed_posts'][] = $post->ID; 

而且同樣我大概可以遵循這樣的事情該命令刪除那些大於10:

if(sizeof($_SESSION['recently_viewed_posts']) > 10) 
{ 
    array_shift($_SESSION['recently_viewed_posts']); 
} 

但是這不會如果用戶重新加載同一職位幾次很好地工作,你可能最終的東西,如:

Array 
(
    [recently_viewed_posts] => Array 
     (
      [0] => 456 
      [1] => 456 
     ) 

) 

期望的行爲:

  • 最後的10後的ID將保持在一個陣列
  • 如果訪問後已經在數組中,它會移動到陣列
  • 如果數組的大小的開始或結束10個元素,並且訪問了新的第11個帖子,最舊的帖子ID將被移除並添加新的帖子ID

我不太在意數組的哪一側(開始或結束)新帖子是開着的,只要它是一致的。我並不在乎陣列鍵是什麼。

完成此操作的最佳方法是什麼?

我試着尋找類似的問題,但沒有拿出任何有用的東西,所以我很抱歉,如果這是一個騙局。

回答

1
if (!isset($_SESSION['recently_viewed_posts'])) { 
    $_SESSION['recently_viewed_posts'] = array(); 
} 
array_unshift($_SESSION['recently_viewed_posts'], $post->ID); 
$_SESSION['recently_viewed_posts'] = 
    array_slice(array_unique($_SESSION['recently_viewed_posts']), 0, 10); 

這推動新條目到陣列的開始,雜草出重複使用array_unique(而保持的項目的第一次出現)和數組限制爲10個條目。最近的帖子將在$_SESSION['recently_viewed_posts'][0]

+0

我只是在想類似的:) +1 – diEcho 2012-01-17 05:41:48

1

使用$post->ID作爲關鍵將使事情更簡單。

if (sizeof($_SESSION['recently_viewed_posts']) >= 10) { 
    array_shift($_SESSION['recently_viewed_posts']); 
} 

if (isset($_SESSION['recently_viewed_posts'][$post->ID])) { 
    unset($_SESSION['recently_viewed_posts'][$post->ID]); 
} 

$_SESSION['recently_viewed_posts'][$post->ID] = 1; 

然後array_keys($_SESSION['recently_viewed_posts'])會給你結果。

+0

我想用一個整數作爲數組的鍵將不保​​留順序 – cwd 2012-01-20 05:19:19

+0

你試過:) – xdazz 2012-01-20 05:44:51

+0

哇,你對。這在php4中的工作方式不同嗎?出於某種原因,我認爲如果您使用數字鍵並執行了print_r,它將以數字順序輸出。猜猜我錯了。謝謝! – cwd 2012-01-20 15:56:41

0

嘗試這樣的事情(未測試,只是邏輯)

function addNew($new,$array) 
{ 
    if(!in_array($new,$array)) 
    { 
    if(sizeof($array) < 10){ 
    array_push($array,$new); 
    } 
    else{ 
    array_shift($array); 
    addNew($new,$array); 
    } 
} 

addNew($post->ID,$_SESSION['recently_viewed_posts']) 
+1

這不會將重複項移動到數組的開始。更實際的是,它不起作用,因爲你沒有通過引用來傳遞數組。 – deceze 2012-01-17 06:04:43

0
# Get the Existing Post History, if there is one, or an empty array 
$postHistory = (isset($_SESSION['recently_viewed_posts']) ? $_SESSION['recently_viewed_posts'] : array()); 

# Remove prior visits 
if($oldKey = array_search($post->ID , $postHistory)) 
    unset($postHistory[$oldKey]); 

# Add the Post ID to the end of it 
$postHistory[] = $post->ID; 

# Trim the array down to the latest 10 entries 
$postHistory = array_values(array_slice($postHistory , -10)); 

# Return the value into the Session Variable 
$_SESSION['recently_viewed_posts'] = $postHistory; 
+1

你可以做'array_slice($ array,-10)'而不是你的雙反。這也不包括重複的條目。 – deceze 2012-01-17 06:03:31

+0

@deceze:公平點。我嘗試使用在線php函數sandpit進行測試,但它沒有像我預期的那樣運行。 (雖然這是我的第一個想法。)並同意 - 不包括重複的情況。但是,糾正了這一點。 – 2012-01-17 06:44:17

相關問題