如何在会话中注册同一变量的多个版本

How to register more than one version of the same variable within a session

我的网站有一个包含数千个零件号的数据库。使用变量“$pn”将这些零件号调入标准模板页面,以便在用户搜索产品时使每个页面独一无二。

例如,代码在模板中声明变量 ($pn),它实际上使用我的数据库中的部件号填充前端页面,例如 'ABC123'。

所以后端看起来像:

Thanks for searching for the $pn, we have this item in stock.

前端看起来像这样:

Thanks for searching for the ABC123, we have this item in stock.

我想知道如何创建一个按钮,将 $pn(例如 ABC123)的当前状态保存到会话中,然后当用户访问不同的零件编号页面时,例如 'DEF456'他们可以再次按下按钮并将第二个状态保存到会话中。

我想保存数据的原因是用户可以浏览站点并在单独的页面上构建他们感兴趣的产品列表。类似于篮子,只是存储的值只需要添加到表单字段即可发送。

我只需要在每个会话中保存此数据,我不需要将其保存为 cookie 以存储超过一个会话,或在数据库中进行跨浏览器存储。

我确实尝试过 cookie 方法,但是使用 $pn 变量作为我的 cookie 值只是简单地删除了该值的最后状态,并在我每次访问不同的零件编号页面时创建了一个新值。

我已经四处寻找解决方案,但找不到适合我的正确答案。到目前为止,我得到了类似的东西:

       <?php
        session_start();
        ?>

        <?php

        $pn = $item['pn'];

        // Set session variables
        $_SESSION["partnumber1"] = "$pn";
        $_SESSION["partnumber2"] = "$pn"; //Obviously at the moment this would just overwrite partnumber1 twice so I need a way to register more than once 

        ?>

非常感谢任何帮助,谢谢。

我已经为您的问题提供了一个可能的解决方案的小示例。但是就像我在评论中所说的那样,有很多不同的方法可以做到这一点。希望这会让你朝着正确的方向前进。

这段代码的想法是我们保留一个数组,其中包含所有访问过的部分作为键。如果我们发现一个部分已经设置在我们的数组中,我们会更新该值,以便我们可以跟踪他们访问每个部分的次数。如果尚未设置,我们添加元素并将计数器设置为 1。

if(isset($_SESSION['parts'][$pn])){
    $_SESSION['parts'][$pn]++;
} else {
    $_SESSION['parts'][$pn] = 1;
}

现在如果你想对数组做一些事情,你可以这样做:

foreach ($_SESSION['parts'] as $key => $value) {
    echo 'you have visited part' . $key . ' a total of ' . $value . 'times';
    //You can do whatever you want with the information here.
}

根据要求,这里是使用会话在其中存储数组的小示例。

有 class 个零件。您可以将它放在单独的文件中,并将其包含在任何需要的地方。对于单独的文件,请使用代码下方的部分和上面的示例 - class 部分后括号之间的代码...

<?php

session_start();

//your code

class Parts {
    private $storage = [];

    public function __construct() {
        if (session_status() == PHP_SESSION_NONE) {
            session_start();
        }
        // Ref to session, you can access it directly, but if you want to change place, where parts should be stored, you can simply change it here without editing another lines of code
        $this->storage = &$_SESSION['parts'];
    }

    public function addPart($part) {
        if ($this->storage === null || !in_array($part, $this->storage)) {
            $this->storage[] = $part;
        }
        return $this;
    }

    public function removePart($part) {
        $this->storage = array_filter($this->storage, function($a) use ($part) { return $a !== $part; });
        return $this;
    }

    public function getParts() {
        return $this->storage;
    }

    public function setParts($parts) {
        $this->storage = $parts;
        return $this;
    }
}

$parts = new Parts();
$parts
    ->addPart(1)
    ->addPart(2)
    ->addPart(3)
    ->removePart(2);

var_dump($parts->getParts());

$allParts = $parts->getParts();

// Iterate over each part in storage
foreach ($allParts as $part) {
    // echo one part
    echo $part;
}