json_decode,array和foreach的错误

时间:2021-09-04 08:10:30

I use this code for Virtuemart:

我在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().

但是我得到致命的错误:不能使用stdClass类型的对象作为数组...第4行。如果我在json_decode($ _ SESSION ['__ vm'] ['vmcart'])添加true,我会收到警告:提供的参数无效对于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: *.com/questions/28691203/how-to-remove-a-single-product-from-mod-virtuemart-cart

附:我是php的初学者,根本不知道json_。代码由链接建议:*.com/questions/28691203/how-to-remove-a-single-product-from-mod-virtuemart-cart

1 个解决方案

#1


1  

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

$ cart-> cartProductsData的行为类似于数组,但它实际上是一个对象

try this: change

试试这个:改变

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

to

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

#1


1  

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

$ cart-> cartProductsData的行为类似于数组,但它实际上是一个对象

try this: change

试试这个:改变

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

to

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