Heidel
Heidel

Reputation: 3262

php save array of values

I need to save last 10 viewed products in $_SESSION, so I try to use code below, but in this case $_SESSION['lastViewedProductsList'] keeps only last $product

$title = $node->title;
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; 
$img = $node->uc_product_image['und'][0]['filename'];
$product = array('title' => $title, 'url' => $url, 'img' => $img);

if (!isset($_SESSION['lastViewedProductsList'])) {
  $_SESSION['lastViewedProductsList'] = $product;
} else {
  $_SESSION['lastViewedProductsList'] = $product;
}

How to save last 10 products?

Upvotes: 0

Views: 82

Answers (3)

Nicolas P.
Nicolas P.

Reputation: 84

$title = $node->title;
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; 
$img = $node->uc_product_image['und'][0]['filename'];
$product = array('title' => $title, 'url' => $url, 'img' => $img);

if (!isset($_SESSION['lastViewedProductsList'])) {
    // If the SESSION parameter does not exists, we create it as an array
    $products = array($product);
} else {
    // Else, we add the product in it
    $products = $_SESSION['lastViewedProductsList'];
    $products[] = $product;
    // We check if the array has more than 10 rows
    if(count($products) > 10){
        // If that's the case, we remove the first line in it to keep 10 rows in it
        array_shift($products);
    }
}

$_SESSION['lastViewedProductsList'] = $products;

If you want to check if the product is already in the array, check this solution: PHP: Check if value and key exist in multidimensional array

Upvotes: 1

A. Jain
A. Jain

Reputation: 157

Try This:

$title = $node->title;
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; 
$img = $node->uc_product_image['und'][0]['filename'];
$product = array('title' => $title, 'url' => $url, 'img' => $img);

if (!isset($_SESSION['lastViewedProductsList'])) {
$_SESSION['lastViewedProductsList'][] = $product;
} else {
$_SESSION['lastViewedProductsList'][] = $product;
}

Upvotes: 1

Riccardo Bonafede
Riccardo Bonafede

Reputation: 606

You can convert your array in json format with json_encode() function and save it in your session. Or you can even use php serialize, but i personally prefer json becouse object serialization may lead to some vulnerabilities

Upvotes: 1

Related Questions