0

I use this code for Virtuemart:

$product_id_to_remove = 3;
$cart = json_decode($_SESSION['__vm']['vmcart']);
foreach($cart->cartProductsData as $k => $v){
  if($v->virtuemart_product_id == $product_id_to_remove) unset($cart->cartProductsData[$k]);
}
$_SESSION['__vm']['vmcart'] = json_encode($cart);

but I get the fatal error: Cannot use object of type stdClass as array in ... line 4. If I add true at json_decode($_SESSION['__vm']['vmcart']) I get the warning: Invalid argument supplied for foreach().

How to resolve the problem?

p.s. I'm beginner in php and don't know json_ at all. The code is suggested by the link: stackoverflow.com/questions/28691203/how-to-remove-a-single-product-from-mod-virtuemart-cart

Community
  • 1
  • 1
user3892905
  • 376
  • 1
  • 4
  • 14

1 Answers1

1

$cart->cartProductsData behaves like an array but it's actually an object

try this: change

unset($cart->cartProductsData[$k])

to

unset($cart->cartProductsData->$k)
RST
  • 3,899
  • 2
  • 20
  • 33
  • Unfortunately there is one problem: if I replace [$k] to ->$k, the product is being removed but after a while isn't, so I replace back ->$k to [$k] and removing works again but after a while I get stdClass' error, then I replace [$k] to ->$k again and the circle closes – user3892905 Mar 09 '15 at 10:11
  • 1
    This is probably due to having one or more products in cart. Add a check to see if it is just one object or an array of objects. – RST Mar 09 '15 at 12:07
  • Thanks, but I don't know php so well. Can you write conditions for each case? – user3892905 Mar 09 '15 at 17:21
  • Research a little, you want to learn, right? Otherwise I will have to send you an invoice, so I can do the work for you. Search for is_object/is_array. – RST Mar 09 '15 at 23:12