PHP: unserialize() doesn't return an array
I have this code below to insert serialized data in a field (order_pictures):
$pictures_id = unserialize($category->getOrderPictures());
array_push($pictures_id, $picture->getId());
$category->setOrderPictures(serialize($pictures_id));
It works ok the first time I execute it. At least, it stores b:0;
in the orde开发者_运维百科r_pictures
field.
But when I execute it again, the value of $pictures_id
is bool(false)
, and I expected an array type.
Any idea?
Regards
Javi
Your problem is that you're trying to unserialize
the contents of $category->getOrderPictures()
before it's ever been initialized, so $pictures_id
is getting boolean false
in it, which is the result of unserialize
failing. Then the array_push()
is failing because $pictures_id
isn't an array.
Try this:
$pictures_id = $category->getOrderPictures();
if($pictures_id)
$pictures_id = unserialize($pictures_id);
else
$pictures_id = array();
array_push($pictures_id, $picture->getId());
$category->setOrderPictures(serialize($pictures_id));
It works ok the first time I execute it. At least, it stores b:0;
And thats it: b:0;
is not an array, but its its a boolean (false
)
Unsing PHPs interactive mode (php -a
)
php > var_dump(unserialize('b:0;'));
bool(false)
php > var_dump(serialize(false));
string(4) "b:0;"
This means, that the serialization probably gives you unexpected results, before you put it into the database. When reading from the database everything works fine, but the content is not, what you exptect.
精彩评论