简体   繁体   中英

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"];
 }
 return $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

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;
if(!in_array($CurrentPage, $_SESSION['pages']) {
    $_SESSION['pages'][] = $CurrentPage;
}

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.

请问array_unique有帮助吗?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM