gpt4 book ai didi

php - 显示 cookie 数组中的 3 个值?

转载 作者:行者123 更新时间:2023-11-29 21:45:11 26 4
gpt4 key购买 nike

我想显示最近要显示的三个搜索。我已经设法使用 cookie 让它显示最后一个值,然后在进行搜索时显示它。但是,如何再添加两个,并且当制作第四个时,它会将最后一个推掉?我认为这是一个数组,但不知道如何去做。该网站允许您在数据库中搜索汽车并将其显示在表格中。下面显示仅用于此目的的代码。如果您需要任何其他代码,请询问。

在 search.php 页面上:

if(isset($_COOKIE['searchCar']))
$searchCar = $_COOKIE['searchCar'];
else
$searchCar = "";

<h2>Search for Cars</h2>
<form action="cars_results.php" method="post">
<p>Enter Car Make or Model: <input type="text" name="searchCar" value="<?=$searchCar?>"></p>
<p><input type="submit" value="Search"></p>
</form>

在 car_results.php 页面上:

$searchCar = $_POST['searchCar'];
setcookie("searchCar", $searchCar);

echo "<table>";
echo "<h2>Previous Searches</h2>";
echo "$searchCar<br><br>";

最佳答案

Cookie 存储只能存储字符串,因此您需要以逗号分隔或 json 格式或类似格式保存最后的搜索。

//Read current cookie
$searchCar = $_COOKIE['searchCar'];
//decode the cookie
$last_searches = json_decode($searchCar);
//add current search term to cookie array
$last_searches[] = $_POST['searchCar'];
//Do Search
//Send Cookie
setcookie("searchCar", json_encode($searchCar));

要显示旧搜索,只需迭代 $last_searches

$searchCar = $_COOKIE['searchCar'];
$last_searches = json_decode($searchCar);
foreach($last_searches as $search){
echo $search;
}

请不要依赖此代码,它只是一个概念;我自己没有测试过

关于php - 显示 cookie 数组中的 3 个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34165805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com