How to convert JSON into an array or string? - php

I'm not sure if I'm allowed to ask these types of questions. Anyway, I have this array value $custom_fields['user_gender'][0] that outputs this:
a:2:{i:0;s:7:"Male";i:1;s:7:"Female";}
I'm not sure how to convert this into an array or string.

The example data looks like it is serialized PHP. Serializing is a way an array, string etc. can be "represented" as a textual string and can later be converted back to the original data format, using a unserialize operation. A serialized string can be stored as text in a database and can be unserialized at any point.
You can unserialize it with:
$array = unserialize($custom_fields['user_gender'][0]);
This should return an array. If you var_dump on $array, you can be sure it's an array.

Related

Best way to json encode an array that has a json encoded value already? PHP

I have an array with multiple items in it one of which is an already encoded json string. I'm wanting to json encode the whole array but in doing so it re-json_encodes the json and adds slashes to it. The only way I've found to fix this is to json_decode the value and then encode the whole array. I feel like this is a waste of resources though and I feel like there has to be a better way. Is doing it that way the best possible way?
Here's a sample of the array I'm trying to json_encode.
$arr = array();
$arr["var1"] = '{"test":"test"}';
$arr["var2"] = 'foo';
$arr["var3"] = 'bar';
If I don't decode the var1 first and I just encode the whole array I get a result like so
{"var1":"{\"test\":\"test\"}","var2":"foo","var3":"bar"}
Notice the slashes in the json object.
json_encode() returns a string containing the json representation of a value.
In the example, a php string is passed as one element of the array '{"test":"test"}', thus json_encode() is encoding it appropriately into json format, with escaped quotes "{\"test\":\"test\"}".
If decoding nested json is a very resource heavy task, a workaround is to use a placeholder instead of the value, {"var1":"PLACEHOLDER","var2":"foo","var3":"bar"}, and then using str_replace() to replace it.
However, simply decoding it as you described is probably a cleaner solution, if its not resource heavy.

Getting value from string by index

I have a string of data formatted like so:
[{"pr_a_w":"10","pr_a_we":"10","pr_c_w":"10","pr_c_we":"10"},{"pr_a_w":"20","pr_a_we":"20","pr_c_w":"20","pr_c_we":"20"},{"pr_a_w":"111","pr_a_we":"11","pr_c_w":"111","pr_c_we":"111"}]
The string doesn't have any index/numbers like a regular array would and I'm finding it difficult to extract individual values e.g. with a regular array I could use:
$string[0]["pr_a_w"]
To get the first instance of "pr_a_w" and I could use:
$string[1]["pr_a_w"]
To get the second instance etc.
Is it possible to get single values from this string based on their number?
What you have there is valid JSON (serialized array of objects), so you could use json_decode to translate the serialized data into a native PHP array:
$array = json_decode('[{"pr_a_w":"10","pr_a_we":"10","pr_c_w":"10","pr_c_we":"10"},{"pr_a_w":"20","pr_a_we":"20","pr_c_w":"20","pr_c_we":"20"},{"pr_a_w":"111","pr_a_we":"11","pr_c_w":"111","pr_c_we":"111"}]',true);
$array will then allow you to do exactly what you stated you'd like to do above.
$array[0]["pr_a_w"]; // will give you 10
$array[1]["pr_a_w"]; // will give you 10
Try like this, No need to access with array index. You will get error if you access wrong index.
$json_arr= json_decode('[{"pr_a_w":"10","pr_a_we":"10","pr_c_w":"10","pr_c_we":"10"},{"pr_a_w":"20","pr_a_we":"20","pr_c_w":"20","pr_c_we":"20"},{"pr_a_w":"111","pr_a_we":"11","pr_c_w":"111","pr_c_we":"111"}]',true);
foreach($json_arr as $row){
echo $row['pr_a_w']."<br>";
}

Save and retrieve a php array through mysql

I want to save a long array in mysql database and when i read that array back from mysql database, i want that array back in proper array format. Is this possible?
Other threads are suggesting to convert array into string using serialise and explode. But will they help me to get proper array back?
Thanks.
You can try it yourself.
As an alternative to serailize(), you can use json_encode().
sidenote: reverse of serialize() is unserialize(), not explode().
sidenote: reverse of json_encode() is json_decode().
sidenote: Very worthwhile to read: Discussion of json_encode() vs serialize()
Usually, serialize and unserialize functions are used for such purposes.
With serialize you can convert your array to a string and than get an array by applying unserialize on string you get from serialize.
And about explode: you may use it too, but than you will need to use implode function to serialize array. But it will work with simplest one dimensional arrays only:
implode(",", array("val1", "val2", "val3")) = "val1,val2,val3"

Is there a PHP function to encode/decode a multidimensional array in a string?

Is there a PHP function to encode a generic multidimensional array as a string and get it back as a multidimensional array?
I need it to store in mysql some data (a drupal computed field to be precise). The array contains just floats and strings.
serialize() and unserialize() do what you describe.
http://www.php.net/manual/en/function.serialize.php
http://www.php.net/manual/en/function.unserialize.php
You could also consider encoding the array as JSON with json_encode() and json_decode(), which gives more readable output, if that is important to you.
I second the use of "json_encode" and "json_decode". I believe the output of "json_encode" is less verbose than PHP's serialize function (since data types are inferred) and is immediately more portable (even though that is not a requirement).
Make sure you pass "TRUE" for the second parameter of "json_decode", otherwise you may get a simple object back, depending on how the original data was encoded.

how to convert json to string

how do i convert a json object to a string
i want to insert a json object to a mysql DB
You might be interested in json_encode().
On the other hand if you already got something json encoded then it already is a string and you can simply store it as-is in the database.
JSON itself is a string.
People use json_encode() and json_decode() to convert objects/arrays of PHP to string and back to objects/arrays.
$array = json_decode($json,true);
$string = implode(",",$array);
Now you can save this string in db as text.

Categories