'json_encode turns array into an object
I am have created a 'liking' system for a site but I'm having a bit of trouble with json_encode and json_decode. I use arrays to store who has liked a post, so I need these 2 functions to make it storable, but for some reason it sometimes saves an object to the database:
{"1":"admin"}
instead of an Array (which I want):
["admin"]
This is my code:
if ($liked_by == NULL){ $liked_by = Array(); }
if (! in_array($user, $liked_by)){
$liked_by[] = $user;
$likes = $row['likes']+1;
$liked_by = json_encode($liked_by);
mysql_query("UPDATE $stream SET liked_by = '$liked_by' WHERE id = ".$id, $db)
or die(mysql_error($db));
mysql_query("UPDATE $stream SET likes = '$likes' WHERE id = ".$id, $db)
or die(mysql_error($db));
} else{
if(($liker = array_search($user, $liked_by)) !== false) {
unset($liked_by[$liker]);
}
$likes = $row['likes']-1;
$liked_by = json_encode($liked_by);
mysql_query("UPDATE $stream SET liked_by = '$liked_by' WHERE id = ".$id, $db)
or die(mysql_error($db));
mysql_query("UPDATE $stream SET likes = '$likes' WHERE id = ".$id, $db)
or die(mysql_error($db));
}
Sorry about using deprecated mysql functions...
I'm just not sure what's happening. Thanks in advance.
Solution 1:[1]
You can use as
json_decode($data,true);
where $data
is the saved data from DB.
The above will return an array and you can manipulate it for further operation.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Abhik Chakraborty |