1

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

8

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

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));
Actually what David L.-Pratte recommends by setting second parameter to true in the json_decode works too. So json_decode(stripslashes($strings), true);
Ah, yes. Of course. I have edited my answer for future reference.
7

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

0

The explode function will get you what you need.

answered Mar 30, 2011 at 19:18

Comments

0
explode(',\\',$string); 

should do the trick.

answered Mar 30, 2011 at 19:19

1 Comment

He needs explode. implode turns an array into a string.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.