I'm working on a shipping calculator and i have a problem,let me tell you what i have and then i'll tell you my problem,
My array and foreach:
$array = unserialize($_SESSION['__vm']['vmcart']);
foreach($array->products as $product){
$price = $product->product_price;
$amount = $product->quantity;
$length = $product->product_length;
$width = $product->product_width;
$height = $product->product_height;
$weight = $product->product_weight;
$supplier = $product->product_unit;
}
and everything works with the above code (That's not my problem)
My problem is:
the calculator has to take all the weight from supplier 1 and add them together and then do the same for supplier 2 (see below)
Example:
Product1 - weight is 5kg and it's from supplier 1
Product2 - weight is 2kg and it's from supplier 1
Product3 - weight is 9kg and it's from supplier 2
supplier 1's weight = to 7kg
supplier 2's weight = to 9kg
The same thing if it's the other way around,
Now what i have tried is a if statement (see below) but all it's doing is adding every products weight together,
if ($supplier =='S1'){
$s1_total_weight += $product->product_weight;
} if ($supplier =='S2'){
$s2_total_weight += $product->product_weight;
}
echo 'Supplier 1 '.$s1_total_weight.'<br>';
echo 'Supplier 2 '.$s2_total_weight.'<br>';
i use the below code to get the supplier number (S1 = supplier 1 - S2 = supplier 2),
$supplier = $product->product_unit;
I'm new to php but i think it has to do with the below code or am i wrong? can it be the if statement?
$product->product_weight
Please let me know if you need any more information,
if you have a better title for this topic please change it :)
Thanks for any help.
$weights = array();
foreach ($array->products as $product) {
if (isset($weights[$product->product_unit])) {
// there was already some weight for this supplier, just add to it
$weights[$product->product_unit] += $product->product_weight;
}
else {
// first time we encounter this supplier, set weight
$weights[$product->product_unit] = $product->product_weight;
}
}
foreach ($weights as $supplier => $totalWeight) {
echo "Total weight for supplier {$supplier} is {$totalWeight}.";
}
Related
I am creating a webshop for a rental company. I want to be able to change the price of items according to amount of days they rent the item. I was already able to get the amount of days, but not sure on how to change the price of an item.
This is my code so far in the cart controller.
The error I get is that $rowId is not defined.
public function getTime(Request $request){
$startD = Carbon::parse($request->input('dateOut'));
$endD = Carbon::parse($request->input('dateIn'));
$length = $endD->diffInDays($startD) + 1;
$total = Cart::subtotal();
$rows = Cart::count();
for ($i=0; $i <$rows ; $i++) {
$item = Cart::get($rowId);
Cart::update(
$rowId, [
'price' => $items->product_price*$length,
]);
}
echo $startD;
echo $endD;
echo $length;
echo $total;
}
If you are updating the price of a specific cart, then you can use such a query.
\DB::statement("update carts set price = ABS(`price` * datediff(?,?)) where id=?", [$dateOut, $dateIn, $cart_id]);
I'm trying to exclude/ignore a specific item from a 'count' in an array which generates a CSV file.
I generate a daily CSV file of orders from Woocommerce;
Each Order is made up of a quantity of varying single products;
I define the CSV Headers manually -eg:
$csv_header = array('Order ID','Company Name','Contact Name','Address 1','Address 2','Suburb','Product 1', 'Product 2', 'Product 3','#Items')
I pull the metadata based on Order IDs:
$result = $wpdb->get_results('SELECT * FROM `'.$wpdb->prefix.'postmeta` WHERE post_id = '. (int)$order_id->ID);
I create an instance of each order and get the items:
$order = new WC_Order((int)$order_id->ID);
$items = $order->get_items();
After getting the details and setting the column for those - eg:
if( $res->meta_key == '_shipping_company'){
$order_line[2] = $res->meta_value;
I then loop to create the invidual item product count and the #items total
foreach ($items as $item ) {
$_count = array_search( $item['name'], $csv_header );
$order_line[$_count] = $item['item_meta']['_qty'][0];
$row_items += $order_line[$_count];
}
$order_line[10] = $row_items;
and add blanks to products not in the order:
for ($i = 0; $i < 37; $i++) {
if( !isset($order_line[$i]) && empty($order_line[$i]) ) {
$order_line[$i] = '';
}
This all works well, but now I need to EXCLUDE a product NOT defined in the $csv_header from the count - bearing in mind that the Order will contain defined products. eg: count products 1-3 but not Product 4.
At the moment if a Product is not defined in $csv-header, it will put a number in my first column in place of the order-id instead of ignoring it.
Any suggestions appreciated.
I have a url like this
http://example.com/index.php?&item_name_1=productnamex&quantity_1=1&amount_1=0&item_number_1=2&on0_2=thumb&option_index_2=1&item_name_2=productnamex&quantity_2=1&amount_2=0&item_number_2=2&on0_2=thumb&option_index_2=1&item_name_3=productnamexx&quantity_3=1&amount_3=0&item_number_3=3&on0_3=thumb&option_index_3=1.....
that sends to a page the values of a shopping card. I want to GET the values item_name_x, quantity_x, amount_x where x the number of each product, group and print them like
Product 1 name - Product 1 Quantity - Product 1 Amount
Product 2 name - Product 2 Quantity - Product 2 Amount
Product 3 name - Product 3 Quantity - Product 3 Amount......
I can't make any change to the page who produce the url.
Can anyone help me?
Thanks in advance for any help you are able to provide.
That's a really bad design, poor you have to deal with it. However, if you're sure that the query string will always be consistent (i.e.: each group will always be complete: name-quantity-amount) you can try this:
$i = 1;
while (isset($_GET['item_name_'.$i])) {
$name = $_GET['item_name_'.$i];
$qty = $_GET['quantity_'.$i];
$amt = $_GET['amount_'.$i];
... // do whatever you want with those 3
$i++;
}
what about this
<?php
$count=count($_GET);
for($i=1;$i=$count;$i++)
{?>
Product <?php $i;?> name - Product <?php echo $i?> Quantity - Product <?php echo $i?> Amount
<?php }?>
My client and I are trying to achieve something that we are maybe not supposed to do. We have a demanding set of non-standard products that include different types of product conditions, e.g. grade B ware etc. In addition product data is coming in in form of feeds from several suppliers. In order not to clutter up the product listing we would like to convert existing, manually edited simple products into grouped ones (or whatever is appropriate) with associated new simple products programmatically on the fly and vice versa whenever necessary, i.e. when there are at least two different sub products.
So far we managed to do this somehow, a test scenario produces the seemingly right product structure – correctly associated products are displayed in the backend, the quantities have been correct before. The problem occurs with the frontend check on 'isSaleable()' for both the grouped product and the associated products, it returns 'false' no matter what we do. When we enforce the display of the qty input boxes and add-to-cart button they will (naturally?) just product the error message 'Please specify the quantity of product(s)'. We tried to set 'is_salable' by different means throughout the code. What else is missing? Any little hint, any advice here would be appreciated!
The code is quite lengthy already, and probably there's already some redundancy in there because of our attempts to somehow fix this. There's a main script that fetches a product collection and compares each entry with the existing supplier feeds. The essential part then is the function call to convert the product:
if (sizeof($newProducts[$productsSku]) > 1 && $_product->getTypeId() == 'simple') {
$newProductQtys = createGroupedProduct($_product, $newProducts[$productsSku]);
}
There are 2 functions for the actual conversion process, one which creates duplicates of the master products (type = simple) and sets their values accordingly:
function createDuplicate($product, $values) {
global $suppliers, $conditions_arr;
$sku = $product->getSku();
$newSku = $sku.'-v'.$suppliers[$values['feed']]['id'];
$qty = $values['qty'];
$feed = $values['feed'];
$cost = $values['cost'];
$item_condition = $values['item_condition'];
$box_condition = $values['box_condition'];
$notes = stripslashes($values['notes']);
$newProduct = $product->duplicate();
$newProduct->setTypeId('simple');
$newProduct->setStoreId(0);
$newProduct->setWebsiteIds(array(1));
$newProduct->setVisibility(2);
$newProduct->setSku($newSku);
$newProduct->setData('media_gallery', array());
$newProduct->setStatus(Mage_Catalog_Model_Product_Status::smileyfrustrated:TATUS_ENABLED);
$newProduct->setPrice((real)($cost + $cost*$suppliers[$feed]['price_increase']));
$newProduct->setTaxClassId(2);
$newProduct->getResource()->save($newProduct);
$productId = $newProduct->getId();
// Check if there is a stock item object
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
$stockItemData = $stockItem->getData();
if (empty($stockItemData)) {
// Create the initial stock item object
$stockItem->setData('inventory_manage_stock_default', 1);
$stockItem->setData('manage_stock',1);
$stockItem->setData('is_in_stock', $qty ? 1 : 0);
$stockItem->setData('is_salable', 1);
$stockItem->setData('use_config_manage_stock', 1);
$stockItem->setData('stock_id',1);
$stockItem->setData('product_id',$productId);
$stockItem->setData('qty',$qty);
$stockItem->setTypeId( $newProduct->getTypeId() );
$stockItem->save();
// Init the object again after it has been saved so we get the full object
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
}
// Set the quantity
$stockItem->setData('qty',$qty);
$stockItem->setData('is_salable', 1);
$stockItem->save();
// $newProduct->assignProduct($newProduct, 1, 1);
$newProduct->setIsSalable(1);
$newProduct->setStatus(Mage_Catalog_Model_Product_Status::smileyfrustrated:TATUS_ENABLED);
$newProduct->save();
$event = Mage::getSingleton('index/indexer')->logEvent($newProduct,$newProduct->getResource()->getType(),Mage_Index_Model_Event::TYPE_SAVE,false);
Mage::getSingleton('index/indexer')->getProcessByCode('cataloginventory_stock')->setMode(Mage_Index_Model_Process::MODE_REAL_TIME)->processEvent($event);
return $productId;
}
and
function createGroupedProduct($product, $newProductsArr) {
global $suppliers;
$origProductId = $product->getId();
$sku = $product->getSku();
$newProductId = array();
$newProductQtys = array();
$qty = 0;
$price = 999999;
$product->setTypeId('grouped');
$product->save();
foreach($newProductsArr as $key => $values) {
$id = createDuplicate($product, $values);
$newProductId[] = $id;
$newProductQtys[$id] = $values['qty'];
// add up all stock quantities of all slave products for master
$qty += $values['qty'];
// determine lowest price among all slave products
$subItemPrice = (real)($values['cost'] + $values['cost']*$suppliers[$values['feed']]['price_increase']);
if ($subItemPrice < $price) $price = $subItemPrice;
}
if (sizeof($newProductId) > 1) {
$products_links = Mage::getModel('catalog/product_link_api');
foreach($newProductId as $key => $id) {
$products_links->assign('grouped', $origProductId, $id);
}
}
// set new values for grouped product according to slave products values
$product->setPrice($price);
$product->getResource()->save($product);
// Check if there is a stock item object
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($origProductId);
$stockItemData = $stockItem->getData();
if (empty($stockItemData)) {
// Create the initial stock item object
$stockItem->setData('manage_stock',1);
$stockItem->setData('is_in_stock', $qty ? 1 : 0);
$stockItem->setData('is_salable', 1);
$stockItem->setData('use_config_manage_stock', 1);
$stockItem->setData('stock_id',1);
$stockItem->setData('product_id',$origProductId);
$stockItem->setData('qty',$qty);
// $stockItem->setTypeId( $product->getTypeId() );
$stockItem->setTypeId('grouped');
$stockItem->save();
// Init the object again after it has been saved so we get the full object
$stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($origProductId);
}
// Set the quantity
$stockItem->setData('qty',$qty);
$stockItem->setData('is_in_stock', $qty ? 1 : 0);
$stockItem->setData('is_salable', 1);
$stockItem->save();
$product->setStatus(Mage_Catalog_Model_Product_Status::smileyfrustrated:TATUS_ENABLED);
$product->save();
$event = Mage::getSingleton('index/indexer')->logEvent($product,$product->getResource()->getType(),Mage_Index_Model_Event::TYPE_SAVE,false);
Mage::getSingleton('index/indexer')->getProcessByCode('cataloginventory_stock')->setMode(Mage_Index_Model_Process::MODE_REAL_TIME)->processEvent($event);
$cache = Mage::getSingleton('core/cache');
$cache->flush();
return $newProductQtys;
}
We tried using the store ID '1' as well and had some success with the shopping cart when the front end used the same kind of mass-product-add-to-cart form that we integrated into the product listing. But the associated products then showed no product name and no image, and not in the admin at all.
If more code from the main script is necessary I will happily provide this.
I have been customising the WP Ecommence plugin to enable a discount for every two items of a certain category. I know that the categories are listed in the $wpsc_cart array but this is not working and I cannot see why. Ideally I would like to scrap this in favor of something simpler, and that is for question part 2 below.
My code-
foreach($wpsc_cart->cart_items->wpsc_cart_item as $cartItemDW){
$ii = 1;
if(in_array('product-type-1',$cartItemDW->category_list) || in_array('product-type-2',$cartItemDW->category_list)){
$ii++;
}
}
//Pull up end count
$prodCount = $ii;
//Round off to even number
if($prodCount % 2){
$prodCount = $prodCount - 1;
}
// Discount for every second one
$prodCount = $prodCount / 2;
// Discount of £70 per second item
$prodCount = $prodCount * 70.00;
// Pass discount to Paypal Array
if($discount > 0){
$paypal_vars += array(
'discount_amount' => $discount
);
}
PART 2
Ideally I would like to find out how to get the category name(s) based upon the item ID in the table _wpsc_cart_contents and then say if it is in certain categories, discount accordingly, seemingly a much easier approach than the foreach that is likely totally off. Can someone please explain how to get the product category based on the product ID?
thanks in advance. Dan
Found the answer 1- in the foreach item -
$prodID = $wpdb->get_row('SELECT * FROM wp_wpsc_item_category_assoc WHERE product_id = "'.$item['prodid'].'"');
if($prodID->category_id == 10 || $prodID->category_id == 5 || $prodID->category_id == 23 || $prodID->category_id == 24 || $prodID->category_id == 25 || $prodID->category_id == 26){
$addQuantity = $item['quantity'];
$i = $i + $addQuantity;
//$i++;
}
and then later, 2- after the foreach item-
$prodCount = $i;
$discount = 70.00 * ($prodCount / 2);
$data['discount_amount_1'] = number_format(sprintf("%01.2f", $discount),$decimal_places,'.','');