Adding item as array in session array in php - php

I am working on a shopping cart project, and I am adding some items in session as array but when I add one item, then it is displaying two items, code is as below :-
if(!empty($_GET['pid'])) {
if(!empty($_SESSION['cart'])) {
$item = array($_GET['id'], $_GET['pid'], $_GET['item_weight'], $_GET['item_quantity'], $_GET['per_item_price'], $_GET['total_price'], $_GET['savings'], $_GET['product_name'], $_GET['type']);
$index = count($_SESSION['cart']);
$_SESSION['cart'][$index] = $item;
} else {
$item = array($_GET['id'], $_GET['pid'], $_GET['item_weight'], $_GET['item_quantity'], $_GET['per_item_price'], $_GET['total_price'], $_GET['savings'], $_GET['product_name'], $_GET['type']);
$_SESSION['cart'] = array($item);
}
}
Any idea what's wrong with my code?

you can do this much more simply using [] to push items to your array:
$_SESSION['cart'][] = array(
'some' => 'stuff'
);

But your problem is you have used array 2 times .. because $item is already in the form of array.. again your are trying to store array to $_SESSION['cart']
$item = array($_GET['id'], $_GET['pid'], $_GET['item_weight'], $_GET['item_quantity'], $_GET['per_item_price'], $_GET['total_price'], $_GET['savings'], $_GET['product_name'], $_GET['type']);
//$_SESSION['cart'] = array($item);
$_SESSION['cart'] = $item;

Related

PHP adding Subarray from an array

This code is now working! (Thanks to all!). It was suggested earlier by a user to not have the two loops. Any advice for how to remove a loop and speed this up a bit?
foreach($deviceList2 as $key => $value)
$items = []; // create a new array to store the items
foreach($itemList2 as $item) {
if ($item[hostid] == $host[hostid]) {
$items[] = $item; // push the item to the empty array
}
}
$host[inspections] = $items; // update the items to the host

How to push value into array after every loop?

$data = json_decode(file_get_contents("php://input"));
$Product=$data->Product;
$items = array();
print_r($items);
foreach($Product as $index => $value)
{
$Product1 = $Product[$index];
array_push($items, $Product1);
}
I need to push $Product1 value into the array for every iteration. How do I do this?
<?php
$data = json_decode(file_get_contents("php://input"),true);// ensure you don't get an std-class object
$Product=$data->Product;
$items = array();
//print_r($items); // you will always print an empty array if you put it here
foreach($Product as $index => $value)
{
$Product1 = $Product[$index];
echo $Product1; // for debug reasons
$items[]=$Product1;
}
echo '<pre>'; //just for the array format
print_r($items); //for debug reasons
This code should fill the array $items with the values you need. Read my comments as well please, maybe we could help more if you gave us the debugging results but still this code should work for you.

How to add value to associative array that store in session?

include('session.php');
$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
$wishlist = array("$productname" => $productcode);
$_SESSION["wishlist"] = $wishlist;
print_r($_SESSION["wishlist"]);
This code set as an array to a session named "wishlist".
The problem is that the session is being replaced. I want to add to the array if it already exists.
So how can I update my array with new data.
I have tried the following.
$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
$lastsession = $_SESSION["wishlist"];
// CHECK IF SESSION IS EMPTY OR NOT
if(empty($lastsession)) {
$wishlist = array("$productname" => $productcode);
} else {
/*
How Can I Update array ???
*/
}
The array output is like so. It is associated not numeric indexed.
And i want result in single array. Not array in array.
[mobile] => iphone_2
Thank you.
In short, you can do this (if I understand the question correctly):
$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
$lastsession = $_SESSION["wishlist"];
// CHECK IF SESSION IS EMPTY OR NOT
if(empty($lastsession)) {
$wishlist = array("$productname" => $productcode);
} else {
array_push($wishlist, array("$productname" => $productcode));
}
array_push is a function that will add information to the end of an array. In this instance, we are using it to add the product array to the current wishlist.
An alternative simple solution would be:
// create a blank array if the session variable is not created
// array_push requires an array to be passed as the first parameter
$wishlist = isset($_SESSION["wishlist"]) ? $_SESSION["wishlist"] : array();
//$wishlist = $_SESSION["wishlist"] ?? array(); // this is for PHP 7+
array_push($wishlist, array("$productname" => $productcode));
// you can then access each product as:
$wishlist["mobile"];
Or replace line 5 from the above code snippet with the following:
$wishlist[$productname] = $productcode;
This would save you from creating an empty array as in line 3.
The advantage that array_push has over this is that you can add multiple products at once such as:
$products = [$productname1 => $productcode1, $productname2 => $productcode2];
array_push($wishlist, $products);
The one thing I have noticed is that you are setting the session to $lastsession as well as using $wishlist. Try and keep duplicate variables to non-existent.
$_SESSION["wishlist"] = array( 'product1' => 'product1 Name' );
// Initial products in session
$temp_session = $_SESSION["wishlist"];
//store products in wishlist in temp variable
$temp_session['mobile'] = 'iphone_2';
// Add new product to temp variable
$_SESSION["wishlist"] = $temp_session;
//Update session
print_r( $_SESSION["wishlist"] );
Set the wishlist data from the session to variable and then just add the new product to this variable. After that update the wishlist data in the session.
$productname = $_GET['productname'];
$productcode = $_GET['productcode'];
// do the same as: $wishlist = !empty($_SESSION["wishlist"]) ? $_SESSION["wishlist"] : [];
$wishlist = $_SESSION["wishlist"] ?? [];
$wishlist[$productname] = $productcode;
$_SESSION["wishlist"] = $wishlist;
print_r($_SESSION["wishlist"]);

How to store product quantities in an array

I have a data array that totals all the items in the cart for all the products as one number.
I've been trying to figure out a way to get a data array count() all the different totals of all the different items in the cart and have them presented in my data layer comma separated. I hope that makes sense.
if ($order->getId()) {
$items = $order->getAllVisibleItems();
$itemIds = array();
$itemNames = array();
$itemPrices = array();
$itemMargins = array();
$itemTypes = array();
$itemGenders = array();
$itemSports = array();
$itemCategoryIds = array();
$itemCategoryNames = array();
/** #var Mage_Sales_Model_Quote_Item $item */
foreach ($items as $item) {
// Get the parent item - it is NOT included in the quote due to
// customizations made by the OrganicInternet module for simple
// product pricing. So I had to come up with another way to get it.
$options = $item->getProductOptions();
$parent = $item->getProduct();
if (array_key_exists('info_buyRequest', $options)) {
if (array_key_exists('cpid', $options['info_buyRequest'])) {
$parentId = $options['info_buyRequest']['cpid'];
$parent = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('name')
->addAttributeToSelect('season')
->addAttributeToSelect('gender')
->addAttributeToSelect('sport')
->addAttributeToFilter('entity_id', $parentId)
->getFirstItem();
}
}
$itemIds[] = $item->getSku();
$itemNames[] = $parent->getName();
$itemPrices[] = $item->getBasePrice() ?: 0;
$itemMargins[] = $this->_calculateMargin($parent, null, $item);
$itemTypes[] = $parent->getAttributeText('season');
$itemGenders[] = $parent->getAttributeText('gender');
$itemSports[] = $parent->getAttributeText('sport') ?: 'Other';
$categories = $this->_getAllCategoryIdsAndNames($item->getProduct());
$itemCategoryIds[] = $categories['id'];
$itemCategoryNames[] = $categories['name'];
}
// # Products
$data['u1'] = count($items);
The above will return:
dataLayer = [{"visitorLoginState":"Logged out","visitorType":"NOT LOGGED IN","visitorLifetimeValue":0,"visitorExistingCustomer":"No","u1":2,"u2":["889623392590","889623135517"]
It shows a total of 2 products for the U1 variable and the two sku's for the u2 variable in the data array.
If i have multiple products for the first sku i want it to seperate the quantities. ie.. "u1":1,1,3
Would i use array_sumor some type of multi-dimensional array to acquire my needs?
If i have multiple products for the first sku i want it to seperate
the quantities. ie.. "u1":1,1,3
It is not exactly clear to me is the relationship between sku and product and which variables in your array refer to which. I make the following presumptions:
1) A product is equivalent to one $items element
2) A sku is a unique $itemIds[] value
I use the array key as a simple way to keep track for each unique sku and the value to keep track of the product count for the sku.
if ($order->getId()) {
$items = $order->getAllVisibleItems();
$itemIds = array();
$itemNames = array();
$itemPrices = array();
$itemMargins = array();
$itemTypes = array();
$itemGenders = array();
$itemSports = array();
$itemCategoryIds = array();
$itemCategoryNames = array();
// My addition (UPDATE: fixed to the correct variable name)
$uniqueItemIds = array();
/** #var Mage_Sales_Model_Quote_Item $item */
foreach ($items as $item) {
// Get the parent item - it is NOT included in the quote due to
// customizations made by the OrganicInternet module for simple
// product pricing. So I had to come up with another way to get it.
$options = $item->getProductOptions();
$parent = $item->getProduct();
if (array_key_exists('info_buyRequest', $options)) {
if (array_key_exists('cpid', $options['info_buyRequest'])) {
$parentId = $options['info_buyRequest']['cpid'];
$parent = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('name')
->addAttributeToSelect('season')
->addAttributeToSelect('gender')
->addAttributeToSelect('sport')
->addAttributeToFilter('entity_id', $parentId)
->getFirstItem();
}
}
// *******************************
// My addition / changes
$sku = $item->getSku();
$itemIds[] = $sku; // I don't use this but keep $itemIds for compatibility
// use the array key to track counts for each sku
if (!isset($uniqueItemIds[$sku])){
$uniqueItemIds[$sku] = 1; // UPDATE: fixed to start at 1 not 0
} else {
$uniqueItemIds[$sku]++;
}
// *******************************
$itemNames[] = $parent->getName();
$itemPrices[] = $item->getBasePrice() ?: 0;
$itemMargins[] = $this->_calculateMargin($parent, null, $item);
$itemTypes[] = $parent->getAttributeText('season');
$itemGenders[] = $parent->getAttributeText('gender');
$itemSports[] = $parent->getAttributeText('sport') ?: 'Other';
$categories = $this->_getAllCategoryIdsAndNames($item->getProduct());
$itemCategoryIds[] = $categories['id'];
$itemCategoryNames[] = $categories['name'];
}
// show # Products
// "u1":1,1,3 NOTE: this should be a string => "u1":"1,1,3"
$data['u1'] = "";
foreach ($uniqueItemIds as $key => $val)
// show unique skus in u2
$data['u2'][] = $key;
// show counts for each sku in u1
if (strlen($data['u1'] == 0)){
$data['u1'] = (string)$value;
} else {
$data['u1'] .= ("," . $value);
}
}
How about something like...
if ($order->getId()) {
.....
.....
.....
/** #var Mage_Sales_Model_Quote_Item $item */
$sku_based_array = array();
foreach ($items as $item) {
......
......
......
$categories = $this->_getAllCategoryIdsAndNames($item->getProduct());
$itemCategoryIds[] = $categories['id'];
$itemCategoryNames[] = $categories['name'];
if (isset($sku_based_array[$item->getSku()])) {
$sku_based_array[$item->getSku()] = $sku_based_array[$item->getSku()]++;
} else {
$sku_based_array[$item->getSku()] = 1;
}
}
// # Products
$data['u1'] = array_values($sku_based_array);
Looking at the code it looks like it will only every return one product as the $parent variable is overwritten to get a first item. I have added a new variable named $itemProductCounts this will be returned to the output $data array as itemProductCounts I suspect this will always equal one.
<?php
if ($order->getId()) {
$items = $order->getAllVisibleItems();
$itemIds = array();
$itemNames = array();
$itemPrices = array();
$itemMargins = array();
$itemTypes = array();
$itemGenders = array();
$itemSports = array();
$itemCategoryIds = array();
$itemCategoryNames = array();
$itemProductCounts = array();
/** #var Mage_Sales_Model_Quote_Item $item */
foreach ($items as $item) {
// Get the parent item - it is NOT included in the quote due to
// customizations made by the OrganicInternet module for simple
// product pricing. So I had to come up with another way to get it.
$options = $item->getProductOptions();
$parent = $item->getProduct();
if (array_key_exists('info_buyRequest', $options)) {
if (array_key_exists('cpid', $options['info_buyRequest'])) {
$parentId = $options['info_buyRequest']['cpid'];
$parent = Mage::getModel('catalog/product')->getCollection()
->addAttributeToSelect('name')
->addAttributeToSelect('season')
->addAttributeToSelect('gender')
->addAttributeToSelect('sport')
->addAttributeToFilter('entity_id', $parentId)
->getFirstItem();
}
}
$itemIds[] = $item->getSku();
$itemNames[] = $parent->getName();
$itemPrices[] = $item->getBasePrice() ?: 0;
$itemMargins[] = $this->_calculateMargin($parent, null, $item);
$itemTypes[] = $parent->getAttributeText('season');
$itemGenders[] = $parent->getAttributeText('gender');
$itemSports[] = $parent->getAttributeText('sport') ?: 'Other';
$categories = $this->_getAllCategoryIdsAndNames($item->getProduct());
$itemCategoryIds[] = $categories['id'];
$itemCategoryNames[] = $categories['name'];
$itemProductCounts[$item->getSku()] = count($parent);
}
// # Products
$data['u1'] = count($items);
$data['itemProductCounts'] = $itemProductCounts;
With that all being said, the code above should get you close to what you need, you should replace the line $itemProductCounts[$item->getSku()] = count($parent); with the correct array with the product counts for that SKU.
Part of the issue with your data here is that everything in an $item is hidden behind an accessor. Rather than creating multitudes of arrays, I would suggest either creating a new object to house the information, or just modifying the $item directly.
Messing with the object directly has the risk of you accidentally using a variable name that exists in a protected or private scope though, so probably best to use your own, like so.
if ($order->getId()) {
$items = $order->getAllVisibleItems();
// only need one array, no need for all data points to have their own
$myItems = [];
/** #var Mage_Sales_Model_Quote_Item $item */
foreach ($items as $item) {
// basic shell
$myItem = [];
// get $options and $parent
// ...
// build your own data object
$myItem['sku'] = $item->getSku();
$myItem['name'] = $parent->getName();
$myItem['price'] = $item->getBasePrice() ?: 0;
$myItem['margin'] = $this->_calculateMargin($parent, null, $item);
$myItem['type'] = $parent->getAttributeText('season');
$myItem['gender'] = $parent->getAttributeText('gender');
$myItem['sport'] = $parent->getAttributeText('sport') ?: 'Other';
$categories = $this->_getAllCategoryIdsAndNames($item->getProduct());
$myItem['categoryId'] = $categories['id'];
$myItem['categoryName'] = $categories['name'];
$myItems[] = $myItem;
}
// At this point, $myItems is manipulable by all the array_* functions
// number of items e.g. 3
$data['u1'] = count($myItems);
// array of skus e.g. ["889623392590","889623392590","889623135517"]
// note: can use objects for $myItem if on PHP 7
// if you like -> notation better (in the loop)
$skus = array_column($myItems, 'sku');
// array of skus with counts e.g. ["889623392590" => 2, "889623135517" => 1]
$skus_with_counts = array_count_values($skus);
// just the counts (assuming indexes on other arrays must match) e.g. [2, 1]
// note: might be useful if you want to keep the counts as an array in dataLayer
$sku_counts = array_values($skus_with_counts);
// if you want this as a comma-separated list for u1, e.g. "2,1"
// note: will also work if you implode $skus_with_counts
$data['u1'] = implode(',', $sku_counts);
// get a list of unique SKUs (both will work), e.g. ["889623392590","889623135517"]
$data['u2'] = array_unique($skus);
$data['u2'] = array_keys($skus_with_counts);
}
Most of these kinds of PHP functions will work on your other data types as well if you want to do counting and clustering, and as you point out, you can run sum operations over them as well if you wish.
PHP array manipulation references: array_column, array_count_values, array_values, implode, array_unique, array_keys.
As a sidebar, Mage_Sales_Model_Quote_Item does have a getParentItemId() method available and a getQtyOptions method, which returns both the quantity and the product model.
I think you are mixing things.
In a simple sistem you should have:
Order has an array of OrderedItems
Each OrderedItem stores ProductObject and OrderedQuantity
And the ProductObject contains all product data.
So in your example instead of counting SKUs you must have $item->quantity field and you should work with that when you add/delete/edit order contents.

how to get the value of an array and get the total numbers of the same value in an array?

$cart = $_SESSION['cart'];
if ($cart) {
$items = explode(',',$cart);
//what should i do next?? the value of $items is 4,4,2,2,2,4
To get array without duplicate use array_unique()
$cart = $_SESSION['cart'];
if ($cart) {
$items = explode(',',$cart);
$unique_items=array_unique($items); // gives 4,2
$result_array=array();
foreach($unique_items as $uni_item)
{
$item_occurence_count=0;
$totalvalue=0;
foreach($items as $item)
{
$item_value=$item;
$totalvalue+=$item_value;
if($item==$uni_item)
{
++$item_occurence_count;
$result_array[$uni_item]=$item_occurence_count;
}
}
}
print_r($result_array); // gives Array ( [4] => 3 [2] => 3 )
Hope this is what required.
I think you’re looking for array_count_values that counts the values in an array.

Categories