在电子商务网站中,我想将最近 5 个查看的项目存储在会话数组中。然后想在页面底部打印它。我需要存储每个产品的 3 个属性。标题、ID 和映像名称。我以以下方式存储在数组中
$_SESSION['recent'][] = array("title"=>$products['title'], "link"=>$_SERVER['REQUEST_URI'], "image"=>$products['image']);
现在我将如何打印值,以便我可以单独访问所有值。请注意,输出应如下所示
Name of the product: product name
ID of the product: X45745
image name of the product: shirt.jpg
只是 foreach 循环,打印项目没有什么特别的。
foreach ($_SESSION['recent'] as $item) {
echo 'product name: ' . $item['title'] . '<br>';
echo 'product ID: ' . $item['link'] . '<br>'; // you store LINK in session, but you wanted to print product ID
echo 'product image: ' . $item['image'] . '<br>';
}
编辑以在下面评论:
<?php
session_start();
// in ths short example code I set an empty array to session['recent'], elsewhere there will be +3 items always when you run the script
$_SESSION['recent'] = array();
// insert three items, code copied from your question
$_SESSION['recent'][] = array("title"=>'title', "link"=>'REQUEST_URI', "image"=>'image');
$_SESSION['recent'][] = array("title"=>'title', "link"=>'REQUEST_URI', "image"=>'image');
$_SESSION['recent'][] = array("title"=>'title', "link"=>'REQUEST_URI', "image"=>'image');
// foreach loop, the same as above
foreach ($_SESSION['recent'] as $item) {
echo 'product name: ' . $item['title'] . '<br>';
echo 'product ID: ' . $item['link'] . '<br>';
echo 'product image: ' . $item['image'] . '<br><br>'; // double <br> to make a gap between loops
}
/*
returns:
product name: title
product ID: REQUEST_URI
product image: image
product name: title
product ID: REQUEST_URI
product image: image
product name: title
product ID: REQUEST_URI
product image: image
*/
?>