开发者

Delete from array help

开发者 https://www.devze.com 2022-12-28 14:29 出处:网络
I have a cookie which stores info in an array. This is for a classifieds website, and wh开发者_JS百科enever users delete their \'ads\' the cookie must also be removed of the ad which was deleted.

I have a cookie which stores info in an array.

This is for a classifieds website, and wh开发者_JS百科enever users delete their 'ads' the cookie must also be removed of the ad which was deleted.

So I have this:

if (isset($_COOKIE['watched_ads'])){
$expir = time()+1728000;
        $ad_arr = unserialize($_COOKIE['watched_ads']);
        foreach($ad_arr as $val){
            if($val==$id){  // $id is something like "bmw_m3_10141912"
                unset($val);
                            setcookie('watched_ads', serialize($ad_arr), $expir, '/');
            }
        }
        }

This doesn't work... any idea why? I think its a problem with the unset part... Also, keep in mind if there is only one value inside the array, what will happen then?

Thanks


You got two bugs here: 1) you unset the $val instead of the array element itself. 2) You set the cookie within the loop to the unknown $ad_arr2 array.

    foreach($ad_arr as $key => $val){
        if($val==$id){  // $id is something like "bmw_m3_10141912"
            unset($ad_arr[$key]);
        }
    }
    setcookie('watched_ads', serialize($ad_arr), $expir, '/');


array_filter seems appropriate:

$array = array_filter($array, create_function('$v', 'return $v != '.$id.';'));


You are correct that you are using unset incorrectly. The manual on unset states:

If a static variable is unset() inside of a function, unset() destroys the variable only in the context of the rest of a function. Following calls will restore the previous value of a variable.

When you use 'as' you're assigning the value of that array element to a temporary variable. You want to reference the original array:

foreach ($ad_arr as $key => $val)
...
            unset($ad_arr[$key]);
...
0

精彩评论

暂无评论...
验证码 换一张
取 消