dongming8867 2015-12-10 07:39
浏览 63
已采纳

unserialize()函数不能使用php使用多个索引

I'm storing data in cookie using serialize/unserialize function. Unserialize function does not working when i add new item to array.

Code

$storedArr = array();
        if(isset($_REQUEST['sendProductId'])){
            $newItem = $_REQUEST['sendProductId'];
            $storedArr[] = $_COOKIE['productID'];
            array_push($storedArr, $newItem);
            $cookie_name = 'productID';
            setcookie($cookie_name, serialize($storedArr), time() + (86400 * 30));
        }
        $cookieData = $_COOKIE['productID'];
        $data = unserialize($cookieData);
        print_r($data);

Response on Single array index

Array ( [0] => [1] => 50 ) 

Response on when adding new item to array

Array ( [0] => a:2:{i:0;N;i:1;s:2:"50";} [1] => 50 ) 

Please guide me where i'm wrong. Thanks

  • 写回答

1条回答 默认 最新

  • dongshi9407 2015-12-10 07:51
    关注

    i see logical issue in your code, when you get data from cookie as it is serialized you have to first unserialize it then use

    $storedArr[] = $_COOKIE['productID'];
    

    change to

    $storedArr = !empty($_COOKIE['productID']) ? unserialize( $_COOKIE['productID'] ):array();
    

    it should solve your issue.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?