在 php 中存储并打印最后 5 个查看的项目

Store and print last 5 viewed item in php

在电子商务网站中,我想将最后 5 个查看的项目存储在 session 数组中。然后想把它打印在页面底部。我需要存储每个产品的 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

*/ 
?>