Unable to un-serialize an array of arrays with PHP - php

The array in the database is stored as a serialized string, such as this:
a:1:{i:0;a:4:{s:8:"category";s:26:"Category Name";s:4:"date";s:0:"";s:8:"citation";s:617:"617 Char Length String (shortened on purpose)";s:4:"link";s:0:"";}}
It's structure should resemble the following when unseralized:
array {
id => array { category => Value, date => Value, citation => Value, link => Value }
}
The php code I'm using is:
$prevPubs = unserialize($result[0]['citations']);
The $result[0]['citations'] is the serialized string. $prevPubs will return false. Which indicates an error if I'm not mistaken.
Any help would be greatly appreciated.

b:0 is boolean:false in serialized format. Unserialize would NOT return that exact string, it'd just return an actual boolean FALSE. This means that whatever you're passing into the unserialize call is not a valid serialized string. Most likely it's been corrupted somehow, causing the unserialize call to fail.

in order to handle serialized multidmensional arrays and mysql use this:
<?php
//to safely serialize
$safe_string_to_store = base64_encode(serialize($multidimensional_array));
//to unserialize...
$array_restored_from_db = unserialize(base64_decode($encoded_serialized_string));
?>
i'm pretty sure serialized string in your database is corrupted

You have to unserialize the whole string
$result = unserialize($serialized);
and then use the $result[0]['citation'] index of the result array.

Related

saving array to db but is serialized as a string

I'm saving an array to the db but when I do the array is getting quotes around it from the start to end
e.g
"[{"id":"1","country":"New Zealand","shipping_rate":"1"},{"id":"2","country":"Australia","shipping_rate":"2"}]"
the array shouldn't be quoted at the start and the end when saving but this is happening. When I check my model on the shipping field that is an array I tried to trim it but it's says it can't because it says it's an array, so the problem is when it's being saved to the db for that field
The array should just look like this when being saved unquoted
[{"id":"1","country":"New Zealand","shipping_rate":"1"},{"id":"2","country":"Australia","shipping_rate":"2"}]
mysql doesn't save arrays, it saves strings. When saving an array it is by design that it serializes the array into a string.
If you are using MySql 5.7.8 or later you can use the JSON data type.
https://dev.mysql.com/doc/refman/5.7/en/json.html
You can't save an array in the mysql directly it will throws exception, you should convert it in a string(use json_encode()) and save it in mysql in either varachar/text type field.
Again when you get the data from db, convert it in an array(use json_decode()) and then use it.
u must convert json string to array :
<?php
$json_string= '[{"id":"1","country":"New Zealand","shipping_rate":"1"},{"id":"2","country":"Australia","shipping_rate":"2"}]';
$array = json_decode($json_string,true);
?>
then make a loop with foreach and enter a query in foreach :
<?php
foreach($array as $data){
$id = $data['id'];
$country = $data['country'];
$save= mysql_query("insert into your_database values("$id", "$country")";
}
?>
i home this help

Why does my JSON array turn into an object?

I am trying to unset a value from test_bots.json and save it back, but somehow the data format is being changed in the process.
test_bots.json contains this JSON array:
["John","Vladimir","Toni","Joshua","Jessica"]
My code looks like this:
$good = 'Toni';
$good_arr = file_get_contents('test_bots.json');
$good_arr = json_decode($good_arr);
if(in_array($good, $good_arr)){
$key = array_search($good, $good_arr);
unset($good_arr[$key]);
$good_arr2 = json_encode($good_arr);
file_put_contents('test_bots.json',$good_arr2);
}
The output that's saved is:
{"0":"John","1":"Vladimir","3":"Joshua","4":"Jessica"}
but I want the output to look like:
["John","Vladimir","Joshua","Jessica"]
I tried to unserialize the array before saving it, but it's not working.
Why is this happening?
In order for json_encode to convert a PHP array with numeric keys to a JSON array rather than a JSON object, the keys must be sequential. (See example #4 in the PHP manual for json_encode.)
You can accomplish this in your code by using array_values, which will reindex the array after you have removed one of the items.
$good_arr2 = json_encode(array_values($good_arr));

PHP json_decode return empty array

I just test this sample from php doc (http://au2.php.net/manual/en/function.json-decode.php)
here is my code:
<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; echo json_decode($json, true), '<br />';?>
But it just returns an EMPTY array.
Have no idea why...Been searching around but no solution found.
PLEASE help!
You can validate at following
website: http://jsonlint.com/
You have to use a php "json_decode()" function to decode a json encoded data.
Basically json_decode() function converts JSON data to a PHP array.
Syntax: json_decode( data, dataTypeBoolean, depth, options )
data : - The json data that you want to decode in PHP.
dataTypeBoolean(Optional) :- boolean that makes the function return a PHP Associative Array if set to "true", or return a PHP stdClass object if you omit this parameter or set it to "false". Both data types can be accessed like an array and use array based PHP loops for parsing.
depth :- Optional recursion limit. Use an integer as the value for this parameter.
options :- Optional JSON_BIGINT_AS_STRING parameter.
Now Comes to your Code
$json_string = '{"a":1,"b":2,"c":3,"d":4,"e":5}' ;
Assign a valid json data to a variable $json_string within single quot's ('') as
json string already have double quots.
// here i am decoding a json string by using a php 'json_decode' function, as mentioned above & passing a true parameter to get a PHP associative array otherwise it will bydefault return a PHP std class objecy array.
$json_decoded_data = json_decode($json_string, true);
// just can check here your encoded array data.
// echo '<pre>';
// print_r($json_decoded_data);
// loop to extract data from an array
foreach ($json_decoded_data as $key => $value) {
echo "$key | $value <br/>";
}
you should not use echo because it is an array. use print_r or var_dump .it works fine
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
print_r(json_decode($json, true));
Output:
Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
[e] => 5
)
No, it doesn't return an empty array.
Printing an array with echo just prints a string "Array()".
Use print_r or var_dump to get the structure of the variable.
In newer PHP it will also emit a notice when using echo on an array ("Array to string conversion"), so you shouldn't do it anyway. The manual you've mentioned changed to print_r.
It works fine, but you use wrong method to display array.
To display array you cannot use echo but you need to use var_dump
It works fine as others mention, but when you print the array it is converted to string, which means only the string "Array" will be printed instead of the real array data. You should use print_r(), var_dump(), var_export() or something similar to debug arrays like this.
If you turn on notices you will see:
PHP Notice: Array to string conversion in ...
The example you linked uses also var_dump for the same reason.
var_dump have pretty print in php5.4
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump( json_decode($json));

Get JSON data type from associative array in PHP

Evening everyone!
So, I have with me a JSON string...
{"username":"87db3983285d395ca0af9f","password":"f4f0bb1533ef5034ce6b0a8a7c49a43b","email":"xxx#gmail.com","hnum":3,"splicenum":22,"reg_ip":"71.126.122.217","reg_date":1364175245,"cur_ip":"71.126.122.217","ip_array":["71.126.122.217"],"logins":[],"about":""}
And I decode this string into an associative array in PHP using json_decode().
What I'm doing is trying to make 1 single function for querying a JSON object that has been converted to an associative array in PHP. For this function, I am now working on editing/updating fields.
Example:
json_edit(array(
"set"=>array(
"email"=>"yyy#yahoo.com"
)
));
The key "set" means setting the value of a string or boolean.
Another key would be "push" to append to an array, or "delete" to delete a string or an array.
What I'm wondering is, how can I get the data type of the current array part in PHP?
Meaning, how can I get PHP to say, "OK, the field 'username' is a string, and 'ip_array' is an array"?
I don't want to be able to "set" a string value to what is SUPPOSED to be just a boolean, or, an array.
Is there any way to get the JSON data types in PHP?
Thanks so much in advance.
What about gettype(). Gettype() will return the data type of any variable. http://php.net/manual/en/function.gettype.php
I would use something like this;
<?php
function json_edit($json, $changes = array()){
$decoded = json_decode($json);
foreach($changes as $action => $data){
swith($action){
case 'SET':
foreach($data as $key => $value){
$decoded[$key] = $value;
}
break;
case 'DELETE' :
break;
default;
}
}
return json_encode($decoded);
}
?>

Assigning identifier/name to JSON object in PHP

I'm grabbing data from a mysql database and encoding a JSON object with PHP to use in JS.
On the PHP end, I did this
while($row = mysql_fetch_array($result))
{
$jmarkers = array(
'id'=> $row['id'],
'lat' => $row['lat'],
'lng' => $row['lng'],
etc...
);
array_push($json, $jmarkers);
}
$jsonstring = json_encode($json);
echo $jsonstring;
I can access the data in JS using jQuery, and I made an array to save the JSON data:
$.getJSON("getjson.php", function(data)
{
myMarkers = data;
console.log(myMarkers);
});
I'd planned to access the data in the myMarkers array inside loop, with a statement like this:
var tempLat = myMarkers.jmarkers[i].lat;
The problem is my JSON objects aren't called jmarkers or anything else, they have this generic name "Object" when I print them to the console:
Object { id="2", lat="40.6512", lng="-73.9691", more...},
So I'm not sure how to point to them in my JS array. I looked the PHP JSON encode function and I can't see where to set or change the object name. Any suggestions? Thank you!
That's to be expected. JSON is essentially the right-hand-side of an assignment operation:
var x = {'foo':'bar'};
^^^^^^^^^^^^^---- JSON
The x part is not included, since that's simply the name of the object. If you want your jmarkers text included, it'll have to be part of the data structure you're going to encode:
$arr = array(
'jmarkers' => array(...your data here...);
);
But all this does is add another layer to your data structure for no useful reason.
$jmarkers is simply the identifier on the PHP side for the JSON object. When it gets passed, it converts the array value into a JSON-encoded string and therefore loses the identifier as a result.
In your PHP code at the moment, array_push($json, $jmarkers) is appending an array to your current $json array. You are therefore instancing a two-dimensional array, which will not be retrievable by the jmarkers identifier in your Javascript code. Simply retrieve the data using myMarkers[i] instead.
You... don't. The whole thing is an object. You only need to refer to the elements within.
alert(myMarkers.id);

Categories