显示php会话中最后3个单击图像链接的图像和标题

时间:2014-04-05 14:54:07

标签: php session

我试图找到一种方法来显示最后3个点击图像链接的图像和标题。 以下是链接的构建:

    <a href="?link=test1">
        <img src="http://www.mijncambodja.nl/?link=cambodja-phnom-penh" id="img-phnom-penh" title="phnom penh">
        <div class="disp-div">phnom penh</div>
    </a>

    <a href="?link=test2">
        <img src="http://www.mijncambodja.nl/?link=cambodja-sihanoukville" id="img-sihanoukville" title="sihanoukville">
        <div class="disp-div">sihanoukville</div>
    </a>

    <a href="?link=test3">
        <img src="http://www.mijncambodja.nl/?link=cambodja-siem-reap" id="img-siem-reap" title="siem reap">
        <div class="disp-div">siem reap</div>
    </a>

    <a href="?link=test4">
        <img src="http://www.mijncambodja.nl/?link=cambodja-kampot" id="img-kampot" title="kampot">
        <div class="disp-div">kampot</div>
    </a>

    <a href="?link=test5">
        <img src="http://www.mijncambodja.nl/?link=cambodja-kep" id="img-kep" title="kep">
        <div class="disp-div">kep</div> 
    </a>

所以我希望在会话中看到最后3个点击的图像和标题。每次单击新图像链接时,3个链接中最旧的链接将被销毁。

有人可以帮帮我吗?如果可能的话,在jsfiddle

感谢。

2 个答案:

答案 0 :(得分:1)

每次点击都应该通过PHP脚本。 PHP脚本应该实现队列。 例如(未经测试):

class Image {
    protected $name;
    protected $title;

    public function __construct($name, $title) {
        $this->name = $name;
        $this->title = $title;
    }

    public function getName() {
        return $this->name;
    }

    public function getTitle() {
        return $this->title;
    }

}

class ImageQueue {

    protected static $queue = array();

    public static function addImage($title, $name) {
        $image = new Image($name, $title);
        array_shift(self::$queue);
        array_push($image);

    }

    public static function toArray() {
        $array = array();
        foreach(self::$queue as $image) {
            $array[] = array(
                'name'  => $image->getName(),
                'title' => $image->getTitle()
            );
        }

        return $array;
    }

    public static function saveToSession() {
        $_SESSION['mage_queue'] = self::toArray();
    }

}

答案 1 :(得分:0)

<!DOCTYPE html>之前将此代码放在页面顶部。

$click_id=filter_input(INPUT_GET, 'link', FILTER_SANITIZE_STRING); // Get the image ID sent by the AJAX.

if(!isset($_SESSION['clicks'])) // If the SESSION is not created already, create it.
{
  $_SESSION['clicks']=array();
}

array_unshift($_SESSION['clicks'], $click_id); // Prepend the last click ID to the SESSION array.

if(sizeof($_SESSION['clicks'])>3)
{
    array_pop($_SESSION['clicks']); // If the array size is greater than 3, delete the last index, that is the oldest value.
}

所以你可以通过

获得最后三次点击
$_SESSION['clicks'][0], // Most recent click
$_SESSION['clicks'][1], // Second recent click
$_SESSION['clicks'][2], // Oldest click