I am using this on a shopping cart
if (!empty($_getvars['id'])) {
$data = $session->get('cart');
$data[] = $_getvars['id'];
$session->set('cart', $data);
}
$_getvars['id'] is productid, and on each click, a new array element will be added to the session. It works fine as it is now, but if a product is chosen more than once a new array will be added, how can change it that productid will be array offset and the value will be incremented from 1 each time to reflect the quantity?
$i = 1;
if (!empty($_getvars['id'])) {
$data = $session->get('cart');
$data[$_getvars['id']] = $i++;
$session->set('cart', $data);
}
but this code each time resets to 1. How to fix it? Or any better array structure for a shopping cart?
If it's not set, set it to zero, then always add one.
if (!empty($_getvars['id'])) {
$data = $session->get('cart');
if(!isset($data[$_getvars['id']]){
$data[$_getvars['id']] = 0;
}
$data[$_getvars['id']] += 1;
$session->set('cart', $data);
}
Or you could add a dynamic quantity
if (!empty($_getvars['id'])) {
$data = $session->get('cart');
if(!isset($data[$_getvars['id']]){
$data[$_getvars['id']] = 0;
}
// $_GET['qty'] OR 1, if not set
$qty = (!empty($_getvars['qty']))? $_getvars['qty']: 1;
$data[$_getvars['id']] += $qty;
$session->set('cart', $data);
}
Related
I have two arrays which have items and quantities and they are asociated by the index of the arrays. Example:
Items=XL,M,XL,S
Quantities=5,2,4,7
What I want to achieve is to remove the repetitive items and sum their quantities:
Items=XL,M,S
Quantities=9,2,7
$uniqueTallesTotalesC = array_unique($tallesTotalesC);
for($i=0;$i<Count($uniqueTallesTotalesC);$i++){
for($e=0;$e<Count($cantidadesTotalesC);$e++){
if($uniqueTallesTotalesC[$i]==$tallesTotalesC[$e] && $e > $i){
$cantidadesTotalesC[$i] = $cantidadesTotalesC[$i] + $cantidadesTotalesC[$e];
} else{
}
}
}
You can just blindly zip-merge them together with summation:
$items = explode(',', 'XL,M,XL,S');
$quantities = explode(',', '5,2,4,7');
if(count($items) !== count($quantities)){
throw new RuntimeException('Count mismatch');
}
$final = [];
for($i = 0; $i < count($items); $i++) {
if(!isset($final[$items[$i]])){
$final[$items[$i]] = 0;
}
$final[$items[$i]] += $quantities[$i];
}
var_dump($final);
Outputs:
array(3) {
["XL"]=>
int(9)
["M"]=>
int(2)
["S"]=>
int(7)
}
Demo: https://3v4l.org/6A5ZC
There's probably an autovivification that I'm missing that could simplify this greater.
I suggest you to create another array variable to hold the new items' quantities:
// I imagine these are your existing variables from your sample code
$tallesTotalesC = array('XL','M','XL','S');
$cantidadesTotalesC = array(5,2,4,7);
$uniqueTallesTotalesC = array_unique($tallesTotalesC);
// This will reset the indexes of the unique items array
$uniqueTallesTotalesC = array_values($uniqueTallesTotalesC);
// init a new quantities array with zeros
$uniqueCantidadesTotales = array_fill(0, count($uniqueTallesTotalesC), 0);
if (count($uniqueTallesTotalesC) == count($tallesTotalesC)) {
// all items are unique so no need to loop through and sum the quantities
$uniqueCantidadesTotales = $cantidadesTotalesC;
} else {
foreach($uniqueTallesTotalesC as $newIndex => $item) {
// get all indexes of the item in the old array
$oldIndexes = array_keys($tallesTotalesC, $item);
// for each of the index, get the sum the old quantity to the new quantity
foreach($oldIndexes as $oldIndex) {
$uniqueCantidadesTotales[$newIndex] += $cantidadesTotalesC[$oldIndex];
}
}
}
Hope it helps!
Im not pro in programming
i have a foreach loop that gets the values from a form calculating the total and subtotal
public function salecal()
{
if ($this->input->post())
{
$i = 0;
$data = array();
$subtotal = 0;
foreach($this->input->post('pname') as $d){
$data[] = array(
'pid' => $this->input->post('pid[]')[$i],
'pname' => $this->input->post('pname[]')[$i],
'quantity' => $this->input->post('qty[]')[$i],
);
foreach ($data as $entry) {
$qty = $entry['quantity'];
$pid = $entry['pid'];
$proname = $entry ['pname'];
}
$value = $this->insert_model->get_price($pid); ///pasing the product id to get the the price from database
foreach ($value->result() as $row)
{
$price = $row->price;
}
$total = $price * $qty; ////Total calculation
$subtotal = $subtotal + $total;/////Sub Total Calculation
$i++;
}
$result = compact("proname", "price", "qty", "total","i", "subtotal");
$this->load->view("bill", $result);
}
}
when i run this code im getting only the finally entered products details but the subtotal is correct
but the data inserting form is dynamic
what i want as result is
user will insert several or one item with quantity
data should be calculated and pass the calculated values to view
but currently im getting it only for the last inserted data please help me how to catch all the datas that user insert to form and how to pass them to view
Because your overwriting the variables consequently so it's passing last overwrite value only . you should make array for each one
This how you need to send all data to view using array
<?php
public function salecal()
{
if ($this->input->post())
{
$i = 0;
$data = array();
$subtotal = 0;
$final_array_collection =array();
foreach($this->input->post('pname') as $d){
$total =0; //reset the total to zero for each product
$pid = $this->input->post('pid[]')[$i];
$pname = $this->input->post('pname[]')[$i];
$quantity = $this->input->post('qty[]')[$i];
$value = $this->insert_model->get_price($pid); ///pasing the product id to get the the price from database
foreach ($value->result() as $row)
{
$price = $row->price;
}
$total = $price * $quantity; ////Total calculation
$subtotal = $subtotal + $total;/////Sub Total Calculation
$final_array_collection[] =array("proname"=>$pname, "price"=>$price, "qty"=>$quantity, "total"=>$total,"i"=>$i, "subtotal"=> $subtotal);
$i++;
}
$result = compact("final_array_collection");
$this->load->view("bill", $result);
}
}
?>
I am getting 2 arrays from the database, in both of the arrays there is a capital_payment which is 80 in both of them. So what I am trying to accomplish is that, the user gives a input which I get from $amount, of 90 , then I only select the row which has less than 90 , if the user selects 160 or 160+ i return both the rows, if the user selects 159 I return only one row . So that is basically the criteria I need to work with. I am trying to return the data in a array depending on the criteria. But I am making to many mistakes so need help.
public function GetSellLoanData($token, $amount, $expirationDate, $radioChecked, $orig_id)
{
$result = $this->investment->getLoansBorrowedData($id, $orig_id);
$foo = json_decode(json_encode($result), true);
$amountTemp = 0;
$data = array();
foreach($foo as $investment)
{
//check if input Amount greater than $AmountTemp from for each loop
if($amount > $amountTemp)
{
$data[] = $investment;
//DO a check to see what happens to the array data
foreach($data[] as $check){
}
// see if the new array did not exceed the $amount
//adding rows here
$data[] = $investment;
}else{
break;
}
$amountTemp += $investment['capital_payment'];
}
return $data;
}
}
And also I want to return all the other information in the array selected so I guess my $data array is not right as well.
Made some new changes! Hope this works!
$amountTemp = 0;
$data = array();
foreach($foo as $investment)
{
//check if input Amount greater than $AmountTemp from for each loop
if($amount > $amountTemp + $investment['capital_payment'])
{
$data[] = $investment;
}else{
break;
}
$amountTemp += $investment['capital_payment'];
}
I have a shopping cart, which works just fine, but I would like to store type of goods (for example color, size, etc.).
Here is a function that gets items from shopping cart
public static function getCart() {
if((isset($_SESSION['cart'])) && count($_SESSION['cart'])>0) {
$ids = "";
foreach($_SESSION['cart'] as $id => $quantity) {
$ids = $ids . $id . ",";
}
$ids = rtrim($ids, ',');
$dotaz = dibi::fetchAll("SELECT * FROM eshop_products WHERE idProduct IN ({$ids})");
return $dotaz;
} else {
//do nothing
}
}
And function that adds items to shopping cart
public static function addToCart($data) {
$id = $data['id'];
$quantity = $data['qty'];
$varianta = $data['varianty']; //THIS IS WHAT I NEED TO ADD TO SESSION ARRAY
if(!isset($_SESSION['cart'])) {
$_SESSION['cart'] = array();
}
if(isset($_SESSION['cart'][$id])) {
$_SESSION['cart'][$id] += $quantity;
} else {
$_SESSION['cart'][$id] = $quantity;
}
}
Is there some easy way to do that? I googled some tutorials, but still no success.
Thank you.
Maybe this is a hint for you:
$id = $data['id'];
$quantity = $data['qty'];
$varianta = $data['varianty']; //THIS IS WHAT I NEED TO ADD TO SESSION ARRAY
$cart = array();
array_push($cart, array(
'id' => $id,
'quantity' => $quantity,
'varianta' => $varianta
));
i am building a shopping cart and cant figure out how to store something like this into a session.
[product_id1] = quantity;
[product_id1] = size
[product_id1] = color;
[product_id2] = quantity;
[product_id2] = size;
[product_id2] = color;
...
etc
so when a user select the quantity of a product then selects its color then selects to add to a cart i want the items selected to be added into a session and each item added to the cart , its attributes selected to be added into a session. how would i do this?
many many thanks.
$_SESSION['productid1']['quantity'] = 15;
$_SESSION['productid1']['size'] = 30;
$_SESSION['productid1']['color'] = 'red';
$_SESSION['productid2']['quantity'] = 35;
$_SESSION['productid2']['size'] = 2;
$_SESSION['productid2']['color'] = 'blue';
Don't forget to put session_start() at the beginning of every page to carry the sessions through the pages.
$item[$catalog_number]['quantity'] = 1;
$item[$catalog_number]['size'] = 'XL';
$item[$catalog_number]['color'] = 'yellow';
$_SESSION['cart'][] = $item;
unset($item);
Repeat for each item you are adding. Alternatively you could do:
$item['catalog_number'] = 'ABC-123';
$item['quantity'] = 1;
$item['size'] = 'XL';
$item['color'] = 'yellow';
$_SESSION['cart'][] = $item;
unset($item);
Both will work, just make sure you are consistent. Use only one or the other.
You should create an array in session array for your products:
$_SESSION['products'] = Array();
then you can put products there like this:
$product = Array();
$product['quantity'] = 6;
$product['size'] = 'XXL';
$product['color'] = 'blue';
$_SESSION['products'][] = $product;
$product = Array();
$product['quantity'] = 2;
$product['size'] = 'XL';
$product['color'] = 'blue';
$_SESSION['products'][] = $product;
this will give you numbered array, if you want an associative array, you will just put identifier into []:
$_SESSION['products']['productID'] = $product;