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

时间:2015-01-06 07:58:59

标签: php

在电子商务网站中,我想在会话数组中存储最后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

1 个答案:

答案 0 :(得分:1)

只需预测循环,打印物品没什么特别的。

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

*/ 
?>