I have a string that when I var_dump returns the following
string(20) "{\"key1\":\"key1_value",\"key2\":\"key2_value\"}"
How can I convert that into an array that will return the following when I var_dump?
array(2) { ["key1"]=> string(20) "key1_value" ["key2"]=> string(20) "key2_value" }
Thanks,
Tee
Felix Kling
820k181 gold badges1.1k silver badges1.2k bronze badges
asked Mar 30, 2011 at 19:15
4 Answers 4
It looks like a simple JSON array that got mangled by PHP's magic_quotes
or some other escaping function. Turn off magic_quotes
and run json_decode()
on the string.
// If you cannot disable `magic_quotes` or you escaped it manually, use this
$array = json_decode(stripslashes($strings), true);
answered Mar 30, 2011 at 19:20
Sign up to request clarification or add additional context in comments.
3 Comments
teepusink
Thanks Sander, that works. I was just doing json_decode without the stripslases which was the issue. Also I actually needs to convert that into an array since what you recommended returned an StdObject. So actual code I used is (array) json_decode(stripslashes($strings));
teepusink
Actually what David L.-Pratte recommends by setting second parameter to true in the json_decode works too. So json_decode(stripslashes($strings), true);
Sander Marechal
Ah, yes. Of course. I have edited my answer for future reference.
What you have as data looks like valid JSON. You probably can use json_decode with the second parameter to true (to get an associative array) like this:
$array = json_decode($string, true);
answered Mar 30, 2011 at 19:19
Comments
The explode function will get you what you need.
answered Mar 30, 2011 at 19:18
Comments
explode(',\\',$string);
should do the trick.
answered Mar 30, 2011 at 19:19
1 Comment
gen_Eric
He needs
explode
. implode
turns an array into a string.lang-php