Looping through a 2d session array shopping cart php - php

Im buliding a shopping cart and want to use a 2d array to store the items ID and quantity. When the user goes to the shopping cart I want to be able to grab the Items ID from the array and output the items details from the database
/**************** Adding to the 2d array ***********************/
//Check to see if variable isset and then add item to shopping cart
//$itemID is the ID of the product
//$quantity is the quantity of the product they wish to order
if(isset($_GET['add'])){
$itemID = $_GET['add'];
$quantity = $_POST['quantity'];
$_SESSION['cart'][] = array("id" => $itemID,"quantity" => $quantity);
header('xxx');//stops user contsanlty adding on refresh
}
/******************** Looping through the array **********************/
//need to loop through grab the item ID
//then pull what we need from the database
//This is where I want to grab the id from the array and query the database
$cart = $_SESSION['cart'];
foreach ($cart as $value ){
//works like it should
foreach ( $value as $key=> $final_val ){
echo $key;
echo ':';
echo $final_val;
echo '<br/>';
}
echo '<br/>';
}
The array outputs like so
id:1
quantity:5
id:2
quantity:1
Im having a little trouble figuring out how to seperate the ID and quantity so that I can query the database with the item ID.

foreach ( $value as $key=> $final_val ){
if($key=='id')
{
echo $key;
echo ':';
echo $final_val;
echo '<br/>';
}
}
or you can directly use like $value['id']
something like this will help you..please try.
is this you need?

Related

How to get value numbering ($no++) in foreach?

I have 2 foreach with different query. The first foreach displays the customer name and transaction number.
Transaction number value in the first foreach is not from Database but from looping $no++.
How to get $no++ value from first foreach to store in second foreach based on customer name.
This Code:
$db = new mysqli("localhost","root","","test");
// Query Customer & Transaction No (First Foreach)
$sql_1 = "SELECT nama FROM pesan GROUP BY nama";
$result = $db->query($sql_1);
$no = 1;
foreach($result as $row){
echo $row['nama'].'<br>';
echo ' Transaction No ='.$no++.'<br>';
}
// Query Purchased product details (second Foreach)
$sql_2 = "SELECT product,nama FROM buy";
$result = $db->query($sql_2);
foreach($result as $row){
echo $row['nama'].'<br>';
echo 'Product Name ='.$row['product'].'<br>';
echo 'Transaction No ='.$no++.'<br>'; // transaction no is taken the value of $no++ from the foreach above based on customer name.
}
Result From First Foreach:
farez
Transaction No =1
hardy
Transaction No =2
Result From Second Foreach:
farez
Product Name = TV
Transaction No = 1
hardy
Product Name = radio
Transaction No = 2
you can actually do that in various ways;
One of them is creating an array and holding the name and transaction number in it as $name => $transaction_number form. To do this you can simply change your first foreach to:
/*----- Define Array Here ------*/
$trnoArr = array();
/*----- Define Transacrion Number And Loop through your results------*/
$no = 1;
foreach($result as $row){
/*----- Add your rows to array ------*/
$trnoArr[$row['nama']] = $no;
/*----- Echo Your results ------*/
echo $row['nama'].'<br>';
echo ' Transaction No ='.$no.'<br>';
/*----- Increase Number Value ------*/
$no++;
}
Than in your second loop you can simply get the transaction number from freshly created array like:
foreach($result as $row){
echo $row['nama'].'<br>';
echo 'Product Name ='.$row['product'].'<br>';
echo 'Transaction No ='.$trnoArr[$row['nama']].'<br>'; // Like here
}

Magento get product ids from orders separated by comma

I need to get productID(s) from an order and display this way:
[1234, 7534, 4587]
I am able to get the product IDs this way:
$incrementId = "12345";
$order = Mage::getModel('sales/order')->loadByIncrementId($incrementId);
$items = $order->getAllItems();
$itemcount= count($items);
$meuproduto = array();
$i=0;
foreach($items as $itemId => $item) {
$meuproduto[$i]['id'] = $item->getProductId();
echo implode(", ", $meuproduto[$i]);
}
For example this order had products 2709 and 7048, so I would like to display:
[2709, 7048]
But with the code I have it's showing:
27097048
I have tried str_replace("", ", ", $meuproduto[$i]);, but I get same result. I tried different ways, but always with same result.
print_r($meuproduto[$i]);
results:
Array ( [id] => 2709 ) Array ( [id] => 7048 )
Your echoing out each product rather than the list of products, so put the echo outside of the loop.
You are also never changing $i, so it will always write to the first element of the array, you can just use [] to add an item to the end of an array...
$meuproduto = array();
foreach($items as $itemId => $item) {
$meuproduto[] = $item->getProductId();
}
echo implode(", ", $meuproduto);
You Can Use Folowing code
$meuproduto = array();
foreach($items as $itemId => $item) {
$id = $item->getProductId();
array_push($meuproduto,$id);
}
print_r($meuproduto);

foreach inside while loop returning duplicate data

Context: I have an ordering form, that has a html select and a number input. so a user selects the item and enter the amount they want of that item, these are sent as arrays to the hander page. $_POST['item']; is an array of id's that I want to select product info from the database with. $amount = $_POST['amount']; is just an array of the amounts of each item.
Problem: Each row is being duplicated by the amount of rows there are, so in this case it's returning three rows, but duplicating each one, three times.
Objective: All I'm trying to do is foreach $_POST['item'] get that rows data from the database and show them and the respective amounts in a table, so the user can confirm the order.
handle.php
<?php
$item = $_POST['item']; // array of product ids to select data from db
$amount = $_POST['amount']; // array of amounts of each product the user ordered
$note = $_POST['note'];
$i = 0;
$each = implode(',',$item);
$stmt = $dbh->query('SELECT *
FROM `products`
WHERE `id` IN (' . $each . ')');
<table class="table">
<thead>
<tr>
<th scope="col">Item</th>
<th scope="col">Quantity</th>
<th scope="col">Price</th>
</tr>
</thead>
<tbody>
<?php
while ($row=$stmt->fetch(PDO::FETCH_ASSOC)) {
$product_id = $row['id'];
$product_name = $row['name'];
$product_price = $row['price'];
$row['quantity'] = $amount[$row['id']];
print "<pre>";
print_r($row);
print "</pre>";
?>
<tr>
<td><?php echo $product_name;?></td>
<td><?php echo $row['quantity'];?></td>
<td><?php echo $product_price;?></td>
</tr>
<?php } ?>
</tbody>
</table>
I'm not really sure what you're trying to do, but you are reassigning
$key = array() ;
immediately after your
foreach ($amount as $key)
That's causing your
<td><?php echo $key;?></td>
to try to echo an array because you overwrote the value of $key assigned by the foreach.
Your post does not detail what data is getting duplicated so I can't really address that in this answer.
You are duplicating the same three rows because you are setting
$new = array_combine($item, $amount);
Then your SQL is grabbing the rows
$stmt = $dbh->query('SELECT *
FROM `products`
WHERE `id` IN (' . $each . ')');
Then you're looping over the same items with
foreach ($new as $key => $val) {
If you want to display the items you found in the SQL then you shouldn't have the
foreach ($new as $key => $val) {
inside your while() loop. Your while() is already looping over the rows returned for those items. This assumes you only have one product per item number.
If you expect one or more 'products' to be returned for each item number then you should be executing your SQL while looping through foreach($new), but that doesn't appear to be what the top part of your code is doing.
After some back and forth we've identified the issue: the amounts need to be tied to the item numbers.
You are getting items numbers and quantities as arrays from your HTML. So you need to loop through the items and associate them with your quantities.
// where your qualities will live
$quantities = array() ;
// loop through the array of items you received and match them up with their quantity
foreach($item as $k=>$id) {
$quantities[$id] = $amount[$k] ;
}
Then you can access the quantity in your while loop using:
$row['quantity'] = $quantities[$row['id']] ;

PHP how to check if product exists in cart

Before add it to cart i want to check if that item already exist. If item exist i dont want twice to show the some item in looping. Just increment quantity of existing item in array session.
Session array with items in cart:
Array
(
[0] => Array
(
[id] => 1
[qty] => 1
)
[1] => Array
(
[id] => 1
[qty] => 1
)
)
On Cart page where am looping items form cart i have this:
<?php
$db = require('database.php');
$cart_items = isset($_SESSION['cart']) ? $_SESSION['cart'] : null;
$products = array();
if($cart_items):
foreach ($cart_items as $key => $value)
{
$products[$key] = $value;
$id = (int) $value['id'];
$result = $db->query("SELECT * FROM products WHERE id=$id");
while($row = $result->fetch_object())
{
$products[$key]['id'] = $row->id;
$products[$key]['name'] = $row->name;
$products[$key]['price'] = number_format($row->price, 2);
// check if item exists
// this dont work i dont know how to check this
if($id == $row->id && $value['qty'] == 1)
{
$products[$key]['qty']++;
}
}
}
endif;
?>
And fronted part where i loop cart products:
<tbody>
<?php if($products): ?>
<?php foreach ($products as $product): ?>
<tr>
<td><?= $product['id'];?></td>
<td><?= $product['name'];?></td>
<td><?= $product['price'];?> Eur</td>
<td><input type="text" name="qty" value="<?= $product['qty']; ?>" size="5"> </td>
<td> <i class="glyphicon glyphicon-remove"></i> Remove </td>
</tr>
<?php endforeach; ?>
<?php endif;?>
</tbody>
So problem is when i click 2 times on item with id = 1 i get two new table rows with the some products. My idea is when i click 2 times on product id = 1 just increment quantity on existing product in cart.
Any sugestion for this ?
First of all, use array_column() function to get all the existing product ids from the $products array. And then check whether the particular item exists in the $products array or not, and update the product and/or quantity details accordingly.
So your while() loop should be like this:
while($row = $result->fetch_object()){
$ids = array_column($products, 'id');
if(in_array($row->id, $ids)){
$products[$key]['qty']++;
}else{
$products[$key]['id'] = $row->id;
$products[$key]['name'] = $row->name;
$products[$key]['price'] = number_format($row->price, 2);
$products[$key]['qty'] = 1;
}
}
Also, remove this statement from your foreach loop,
$products[$key] = $value;
Updated:
From OP's comment,
Now problem is in looping products in cart, when i loop products in cart i have duplicate product becouse i add one product 2 times and update quantity. How to prevent double looping one item in cart! If i press 10 times product with id = 1. I dont want 10 new loop items in list i want only update quantity value. Prevent the some item loop in <tr><td> ...</td></tr> ...
Change your code inside the if block in the following way,
$unique_ids = array_unique(array_column($cart_items, 'id'));
foreach ($cart_items as $key => $value){
if(!in_array($value['id'], $unique_ids)) continue;
$id = (int) $value['id'];
$result = $db->query("SELECT * FROM products WHERE id=$id");
while($row = $result->fetch_object()){
$ids = array_column($products, 'id');
if(in_array($row->id, $ids)){
$products[$key]['qty']++;
}else{
$products[$key]['id'] = $row->id;
$products[$key]['name'] = $row->name;
$products[$key]['price'] = number_format($row->price, 2);
$products[$key]['qty'] = 1;
}
}
$key = array_search($value['id'],$unique_ids);
unset($unique_ids[$key]);
}

multidimensional array with unknow key's

I'm having a multidimensional array from which I don't know the keys and I need all key's with their value.
My array is database filled:
$rows[$product_id][$productgroup_id] = $amount
So the array is for example filled with 2 products:
$rows[108][3] = 2
$rows[2][5] = 4
So my array now holds 2 product:
Product_id 108 from productgroup 3 with an amount of 2
Product_id 2 from productgroup 5 with an amount of 4
Now I need to walk through the array and I need the keys and the amount. So I'm thinking in a foreach loop
foreach($rows as $row){
foreach($row as $key => $value){
echo "Key:".$key." Value: ".$value."<br>";"
}
}
But this only echo's the first key, product_id and the amount. But I need the product_id, productgroup_id and the amount. So how do I also get the productgroup_id?
the code you have so far is almost there, you simply need to extract both id's with the foreach loop.
foreach($rows as $product_id => $group){
foreach($group as $productgroup_id => $value){
echo "Product ID:" . $product_id . " Group:".$productgroup_id." Value: ".$value."<br>";"
}
}
If you want to see/debug the array, you could use the php function print_r(), in your case, it will be echo print_r($row).

Categories