I’m trying to create an array to display the last 5 products a customer has viewed.
The array is a 2 dimensional array like below…
$RView= array(
array( ID => “1001”, RefCode => “Ref_01”, Name => “Name_01” ),
…
array( ID => “1005”, RefCode => “Ref_05”, Name => “Name_05” )
);
The array values are retrieved from the products recordset and is designed to function as follows when a customer visits a product page.
- Page will check if a Session Array exists
- If yes, an array variable is created from existing Session
If no, a new array is created. - Array will add the new product details.
- Array will count if there are more than 5 existing products in the array.
- If yes, it will remove the oldest.
If no, moves to next step. - A Session is created/updated from the revised Array.
My current effort is attached below…
Many thanks for any help.
<?php
session_start()
// Get or Create Array
IF (isset($_SESSION['sessRView'])) {
$RView = ($_SESSION['sessRView']); }
ELSE {
$RView = array(array());
}
// Append currently viewed Product to Array
array(array_unshift($RView, $row_rsPrd['PrdID'], $row_rsPrd['RefCode'], $row_rsPrd['Name']));
// Check if more than 5 products exist in Array, if so delete.
IF (sizeof($RView) > 5) {
array(array_pop($RView)); }
// Update Session for next page
$_SESSION['sessRView'] = $RView;
// Display Array
for ($row = 0; $row < 5; $row++)
{
echo "<ul>";
echo "<li><a href='?PrdID=".$RView[$row]["PrdID"]."'>".$RView[$row]["RefCode"]."</a> : ".$RView[$row]["Name"]."</li>";
echo "</ul>";
}
?>
It’s more or less right – just 2 lines need to be changed.
array_unshift($RView, array($prodid,$name,...))foreach ($Rview as $prod) echo $prod['Name']...It should work after you make these changes. You might want to clean up the coding style a bit, though 🙂
EDIT: Oh, I see, when you’re referencing the array in the for loop it doesn’t know that the array has “ProdID” and “Name” indices. When you make an array you have to define the indexes using the => operator.
Add indexes to the array when you array_unshift:
array_unshift($RView, array("ProdID" => $row_rsProd["ProdID"], "Name"...))If row_rsProd isn’t too big, you can just tack the entire row_rsprod onto $RView.
so change array_unshift(…) to just
$RView[] = $row_rsProdThis way the indexes are preserved.
So you can change the stuff in the foreach loop to
echo "<li>..." $prod[0] $prod[1] $prod[2]Hope that helps!