开发者

Unique entries in an array

I have the following that stores the previous 10 URL's into a session:

function curPageURL() {
 $pageURL = 'http';
 if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
 $pageURL .= "://";
 if ($_SERVER["SERVER_PORT"] != "80") {
  $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 } else {
  $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
 }
 ret开发者_运维百科urn $pageURL;
}
//Insert Current URL in SESSION
       $CurrentPage = curPageURL();
       if(strpos($CurrentPage, '/products/'))
        {
        echo "<div class=\"title\">Recently viewed products</div>
<div id=\"recent\">";
       $_SESSION['pages'][] = $CurrentPage;
       if ( Count ( $_SESSION['pages'] ) > 10 )
        Array_Shift ( $_SESSION['pages'] );

How do I make sure only unique entries are stored?

Thanks, B


if(!in_array($CurrentPage, $_SESSION['pages']) {
    $_SESSION['pages'][] = $CurrentPage;
}


instead of $_SESSION['pages'][] = $CurrentPage try $_SESSION['pages'][$CurrentPage] = 1

/edit: to keep items sorted, unset first:

 unset($_SESSION['pages'][$CurrentPage]);
 $_SESSION['pages'][$CurrentPage] = 1;


Just after

$_SESSION['pages'][] = $CurrentPage;

you need to add

$_SESSION['pages'] = array_unique($_SESSION['pages']);

Docs are available here

This method requires less processing, as it's a native function. Performing an 'if' on each item in the array could potentially be quite costly.


Could array_unique be of help?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜