Dynamic Associative Arrays and Sessions

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dubell
Forum Newbie
Posts: 1
Joined: Sun Apr 10, 2011 4:31 am

Dynamic Associative Arrays and Sessions

Post by dubell »

Probably easiest to explain what I am trying to do, to illustrate the impasse I have came to. I have online store with a number of products. Visitors can click on products, clicking brings details of the product came up in a iframe on the right (with a field to enter the quantity), which can than be added to the shopping cart in a separate iframe below it bottom right by click add product (passed using a different script (the one which I am having issues with)). So each time a product is added to the cart, three dynamic hidden fields are passed via post, which are named "product_name", "unit_quantity" and "unit_price".

So for the shopping cart, I want to incorporate an associative array using the three dynamic fields described above("product_name", "unit_quantity" and "unit_price") within a session so that a number of products can be added (hence using an array rather than a variable).

So shopping cart i have done so far reads:

<?php
session_start();

if (!isset ($product_name) && !empty($product_name))
{

if (!session_is_registered("product_info"))
{
$pos=0;
session_register("pos");
$product_info[$pos]= array ( 'product_name'=>$product_name, 'unit_quantity'=>$unit_quantity,
'product_quantity'=>$unit_quantity * $unit_price);
session_register("product_info");
}


?>

Not sure (as I am new to sessions, how to call the array to the screen). I have read through past threads but have not been able to found anything similar to what I am trying to achieve).

Any hints?
fugix
Forum Contributor
Posts: 207
Joined: Fri Mar 18, 2011 8:01 pm

Re: Dynamic Associative Arrays and Sessions

Post by fugix »

1.) the preferred and more reliable way to register a session is to use $_SESSION instead of session_register....eg.

Code: Select all

$_SESSION["pos"] = 0;
and depending on what part of the array that you wanted to see you could use...

Code: Select all

print_r($product_info[$pos]);
which would show you the entire array,or you could pick out something specific by using array_keys(), array_values(), array_search()...something like that
Post Reply