Getting Invalid argument supplied for foreach() by using &

I am trying to re-edit cookie value.

When I don't use &$prod , it doesn't change the array value.

When I use &$prod , it changes the array but I get:

Invalid argument supplied for foreach()

Is there any other way to update existing array or why am I getting this error?

$existingCookie = Cookie::get($cookie);
$arr = json_decode($existingCookie, true);
foreach ($arr as &$prod) {
    if($productId === $prod["pid"]) {
        if($prod["pqty"]!=$productQty){
            $prod["pqty"] = $productQty;
            $arr = json_encode($arr);
            Cookie::put($cookie, $arr, Config::get('cart/cookie_expiry'));
            echo var_dump($arr) . ' - '.$prod["pqty"];
        }
    }
}

I think you want to repair the whole $arr and then after looping, update the cookie just once. This logically direct approach also eliminates the error as well.

The reason that you are getting the error is because you are using & in your foreach expression AND writing $arr = json_encode($arr); inside your loop. The loop is not iterating a "copy" of the input array (as is the default), it is iterating the input array itself because of &$prod . After the two conditions are satisfied, $arr is converted a json string and the foreach loop chokes on it.

$arr=json_decode(Cookie::get($cookie), true);
foreach($arr as &$prod){
    if($prod["pid"]===$productId && $prod["pqty"]!==$productQty){
        $prod["pqty"]=$productQty;
    }
}
Cookie::put($cookie, json_encode($arr), Config::get('cart/cookie_expiry'));
链接地址: http://www.djcxy.com/p/53068.html

上一篇: 如何在Laravel 4中获取@if语句(刀片)中的当前URL?

下一篇: 通过使用&为foreach()提供无效参数