I am not getting the concept of two dimensional arrays in PHP. I am trying to implement a cart system in which an array Session variable store productid and the quantity of it.
For every new entry if it exists its quantity should be increased or if it does'nt then a new id should be added.
Here is my initial code.
function cart_increment_ajax($data, $qtt) {
$_SESSION['count']+=$qtt;
set_cart( $data );
echo $_SESSION['count'];
}
function initialise_cart( ) {
$_SESSION['cart'] =array( );
$_SESSION['totalprice'] = 0;
}
function set_cart( $pid ) {
if(!isset($_SESSION['cart'])) {
initialise_cart( );
}
//else if( int $_SESSION['cart'] pid exists increment count ))
else
// ($_SESSION['cart'] add new pid.
}
I am not getting how to implement the commented lines through Multidimensional associative array ?
A small quick n dirty example of a multi-array in a session keeping a cart
<?php
function add_to_cart($product_id,$count)
{
// no need for global $_SESSION is superglobal
// init session variable cart
if (!isset($_SESSION['cart']))
$_SESSION['cart'] = array();
// check if product exists
if (!isset($_SESSION['cart'][$product_id]))
$_SESSION['cart'][$product_id]=$count;
else
$_SESSION['cart'][$product_id]+=$count;
}
// add some foos and a bar
add_to_cart('foo',2);
add_to_cart('foo',1);
add_to_cart('bar',1);
print_r($_SESSION['cart']);
?>
This will produce
Array
(
[foo] => 3
[bar] => 1
)
HTH
Use the product ID as an index in your array, then simply increment it by using ++.
$_SESSION['cart'][$pid]++;
Related
I'd like to say I already took at this and this answer.
Problem:
I have a session variable called "cart" which looks like this.
array (
'cart' =>
array (
2 =>
array (
0 => '2',
1 => 2,
),
),
)
Inside of cart I want to remove the values behind the key 2 so [0 => 2, 1 => 1]. I also want 2 to begone. So it's just a blank array. cart => []. To acomplish this I have this line.
unset($_SESSION["cart"][$id]);
$id is from a get request. I'll show the code for it if that is needed for clarification. However, the result of the above snippet gives me this instead.
array (
3 =>
array (
0 => NULL,
1 => 1,
),
)
Not only does 2 increment to 3, NULL also appears for some reason.
$_SESSION["cart"] is made here in cart.inc.php
<?php
session_start();
// A cart is structured like this
// cart = [item_id: [item_id, amount], item_id: [item_id, amount]]
// item_id is the key to another array that contains the item_id, again and the amount of that item.
if (isset($_GET["remove"])) {
$id = $_GET["remove"];
// Instead of removing the key "id" and all of the values behind it.
// It only changes item_id into NULL.
unset($_SESSION["cart"][$id]);
}
$id = $_GET["id"];
if (isset($_SESSION["cart"])) {
// If the item already exists in the cart modify the existing
// item values instead of creating a new one.
if (isset($_SESSION["cart"][$id])) {
// If the user has changed the amount then this will run.
// Instead of adding by 1 it changes the amount of whatever
// the new amount is.
if (isset($_GET["amt"])) {
$amt = intval($_GET["amt"]);
$_SESSION["cart"][$id][1] = $amt;
} else {
// to increase the item quantity. So + 1 here.
$_SESSION["cart"][$id][1] = $_SESSION["cart"][$id][1] + 1;
}
} else {
// This is if the cart exists, but that item is one that isn't in the cart.
array_push($_SESSION["cart"], [$id, 1]);
}
} else {
// When the cart doesn't exist, set the new cart session variable.
$_SESSION["cart"] = [$id => [$id, 1]];
}
header("location: ../../index.php");
there are multiple problems, so it is easier to past fixed version here neither in comments:
<?php
session_start();
if (!isset($_SESSION["cart"])) $_SESSION["cart"] = []; // initialize card if needed
if (isset($_GET["remove"])) {
$id = intval($_GET["remove"]);
if (isset($_SESSION["cart"][$id])) unset($_SESSION["cart"][$id]);
}
else { // you want this part to be executed only when you add, not when you remove
$id = isset($_GET["id"]) ? intval($_GET["id"]) : 0; // check that id is actually passed and covert it immediately
if ($id > 0) {
$prev_amt = isset($_SESSION["cart"][$id]) ? $_SESSION["cart"][$id][1] : 0; // initialize previous amount
$amt = isset($_GET["amt"]) ? intval($_GET["amt"]) : ($prev_amt + 1); // intialize amount
if ($amt > 0) $_SESSION["cart"][$id] = [$id, $amt];
}
}
header("location: ../../index.php");
I have a little script system. It replaces the array but I need it to add to the array. This is what I have:
$_SESSION['cart']=array(); // Declaring session array
array_push($_SESSION['cart'],'item1'); // Item added to cart
If after this I submit:
$_SESSION['cart']=array(); // Declaring session array
array_push($_SESSION['cart'],'item2'); // Item added to cart
It will contain item2 in array not item1 and item2.
How can I get it to do this?
So I changed up my code a bit and not when I push for example the code below twice it will overwrite the item. How can I make it add another one instead?
array_push($_SESSION['cart']['itemName'] = 13.99);
It seems that you are recreating the array on the second set of code meaning that you will delete everything already in the array. Did you try just array_push without the $_SESSION['cart']=array(); for the second set of code? If not try getting rid of that first line and see if it works.
Use this syntax to append:
$_SESSION['cart'][] = 'item1';
$_SESSION['cart'][] = 'item2';
Edit:
// declare only if needed
if (!array_key_exists('cart', $_SESSION)) $_SESSION['cart'] = array();
// when adding an item at any future time once $_SESSION['cart'] exists:
$_SESSION['cart'][] = array(
'itemName' => 'my item',
'price' => 13.99
);
By calling this line every time :
$_SESSION['cart']=array();
You are cleaning out your cart session. If you wrap that in an if statement as well to check whether the array has already been instantiated, then you won't clean it out each time and you should be able to add to it as expected:
if (!isset($_SESSION['cart'])) {
$_SESSION['cart']=array();
}
You are emptying your array before you add to it you declare $_SESSION['cart'] to equal a new empty array
U declared 2 times $_SESSION['cart']. Remove second declare and you should be good to go.
EDIT :
U don't use correct syntax for array_push.
PHP.net : array_push()
If i understood correctly - the index of key (numeric since array_push) bothers you.
U can bypass by using this code :
$_SESSION['cart'] = array();
$_SESSION['cart']['itemName'] = 12.50;
$_SESSION['cart'] = $_SESSION['cart'] + array("blabla" => 13.99);
print "<pre>";
print_r($_SESSION);
print "</pre>";
Result :
Array
(
[cart] => Array
(
[itemName] => 12.5
[blabla] => 13.99
)
)
LAST EDIT : (!?!)
function set_item_price($itemName, $itemPrice)
{
if(!isset($_SESSION['cart'][$itemName]['itemPrice']))
$_SESSION['cart'][$itemName]['itemPrice'] = $itemPrice;
else
echo "Item Already exists \n <br>";
}
function add_to_cart($itemName, $quantity)
{
if(!isset($_SESSION['cart'][$itemName]['quantity']))
$_SESSION['cart'][$itemName]['quantity'] = $quantity;
else
$_SESSION['cart'][$itemName]['quantity'] += $quantity;
}
// Adding item1 - price 12.50
set_item_price("item1", 12.50);
// Adding item1 - quantity - 2 & 3
// OutPut will be 5
add_to_cart("item1", 2);
add_to_cart("item1", 3);
// Adding item3 - price 15.70
set_item_price("item3", 15.70);
// Adding item1 - quantity - 5
add_to_cart("item3", 5);
print "<pre>";
print_r($_SESSION);
print "</pre>";
?>
RESULT :
Array
(
[cart] => Array
(
[item1] => Array
(
[itemPrice] => 12.5
[quantity] => 5
)
[item3] => Array
(
[itemPrice] => 15.7
[quantity] => 5
)
)
)
Otherwise check on this thread :
Stackoverflow : how-to-push-both-value-and-key-into-array-php
I have a problem updating a multidimensional array in PHP. I'm trying to implement am e-commerce website for a project and I am having problems with the shopping cart implementation.
Basically, I use a session to track the items the user adds to the shopping cart. Here's my logic in plain Pseudo code that is executed once the user clicks the add button after specifying a quantity to add for a product:
RETRIEVE 'cartItems' 2D array from SESSION array
IF 'cartItems' array does not exist in the session create new empty array and add the cartItem sub array to it with the qty and productID
ELSE Loop through the array retrieved from the SESSION array, find the product ID that matches the given product ID (index 0) and update the qty for that subarray (index 1).
Here is my PHP script addToCart.php which in turn calls another function in another script file that is included in it:
<?php
require_once("cart_utility.php");
session_start();
// Script for adding a given product to the client's cart through the use of Ajax and sessions
// retrieve values from ajax request
$productID = $_GET["productID"];
$qty = $_GET["qty"];
$cartItems = null;
// use sessions to add the items to the user's cart
// retrieve the multi-dimensional cart array if it exists, otherwise create one and add it
if(isset($_SESSION["cartItems"])){
$cartItems = $_SESSION["cartItems"];
}
else{
$cartItems = array();
}
addQtyForProduct($productID, $qty, $cartItems);
$_SESSION["cartItems"] = $cartItems;
print "Session cartItems after function return: ";
var_dump($_SESSION["cartItems"]);
// return info string with new qty of cart items
print ("success-" . getTotalCartItems($cartItems));
?>
And here's the other script file that does the handling of inserting and updating the array:
<?php
// Utility functions for retrieving items from the 2D cart items array
/* The array structure is given as (example values):
* | productID | qty |
* 0 | 1 | 3 |
* 1 | 2 | 1 |
* 2 | 5 | 8 |
* 3 | 8 | 3 |
*/
// increments the qty for the given product. If it does not exist then it is added into the main session array
// $cartItems: the main 2D array with the structure given above, pass by reference to change the array
function addQtyForProduct($productID, $qty, &$cartItems)
{
foreach($cartItems as $cartItem)
{
var_dump($cartItem);
if($cartItem[0] == $productID){
//print "Quantity given to increment: $qty";
//var_dump($cartItem);
print "Qty in current session array: $cartItem[1]";
$cartItem[1] += $qty;
print "New qty in cartItem array: $cartItem[1]";
return;
}
}
// not found, therefore add it to the main items array
array_push($cartItems, array($productID, $qty));
}
// returns the total number of items in the cart
function getTotalCartItems($cartItems)
{
$total = 0;
foreach($cartItems as $cartItem)
$total += $cartItem[1];
return $total;
}
?>
I have placed some var_dump statements and can confirm that upon returning from the function 'addQtyForProduct', the array is not updated. But why? I pass the array by reference to directly alter it's contents.
It successfully adds on the first time when there is no existing array but fails to increment if the array exists.
Also, the values are successfully incremented in the 'addQtyForProduct' function but the array somehow is not updated when it returns from the function.
I would gladly appreciate some help on this. I've been trying to understand this for days now and It's driving me nuts.
As read on this page you should use references. Add a & in front of your $cartItem and your script should work. Right now PHP stores a 'copy' of every value in your array in $cartItem, rather than it's reference. So currently you are editing a copy of the original, rather than the original array.
I have an issue on how can I update my Previous array ?
What currently happening to my code is its just adding new session array instead of updating the declared key here's my code:
foreach ($items_updated as $key => $added)
{
if ($id == $added['item_id'])
{
$newquantity = $added['item_quantity'] - 1;
$update = array(
'item_id' => $items['item_id'],
'item_quantity' => $newquantity,
);
}
}
Session::push('items', $updated);
$items = Session::get('items', []);
foreach ($items as &$item) {
if ($item['item_id'] == $id) {
$item['item_quantity']--;
}
}
Session::set('items', $items);
If you have nested arrays inside your session array. You can use the following way to update the session: $session()->put('user.age',$age);
Example
Supppose you have following array structure inside your session
$user = [
"name" => "Joe",
"age" => 23
]
session()->put('user',$user);
//updating the age in session
session()->put('user.age',49);
if your session array is n-arrays deep then use the dot (.) followed by key names to reach to the nth value or array, like session->put('user.comments.likes',$likes)
I guess this will work for you if you are on laravel 5.0. But also note, that I haven't tested it on laravel 4.x, however, I expect the same result anyway:
//get the array of items (you will want to update) from the session variable
$old_items = \Session::get('items');
//create a new array item with the index or key of the item
//you will want to update, and make the changes you want to
//make on the old item array index.
//In this case I referred to the index or key as quantity to be
//a bit explicit
$new_item[$quantity] = $old_items[$quantity] - 1;
//merge the new array with the old one to make the necessary update
\Session::put('items',array_merge($old_items,$new_item));
You can use Session::forget('key'); to remove the previous array in session.
And use Session::push to add new items to Session.
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.
There's no need for the extra array() around array_unshift and array_pop.
When you use array_unshift you're pushing an array of items (not the id/codes individually) - I think you mean array_unshift($RView, array($prodid,$name,...))
What if $RView doesn't have 5 elements? In that case you're accessing undefined array indices (which may or may not show an error). Change it to a foreach loop: e.g.
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_rsProd
This way the indexes are preserved.
Alternatively you can change the indicies in the for loop to match. Right now the array you unshift onto $RView is 0-based - $RView[0][0] is the product ID for the first product, etc.
So you can change the stuff in the foreach loop to
echo "<li>..." $prod[0] $prod[1] $prod[2]
Hope that helps!